Ad

Change Background-image With Attribute Value

I have this link:

<div class="wp-show-posts-inner" data-src="http://maria138.coroleu.com/wp-content/uploads/2018/09/foto1.jpg"></div>

I need to change background-image url from another class with data-url on hover event. I try this right now but doesn't work:

var bg_img = jQuery('.wp-show-posts-inner').attr('data-src');    
jQuery('.wp-show-posts-inner').on('mouseover',function() {    
  jQuery('.home-banner .bg').css({'background-image': "url('"+bg_img+"')"});
});

This script get me this result:

element.style {
  background-image: url((unknown));
}

i need this:

<div class="bg" style="background-image: url(http://maria138.coroleu.com/wp-content/uploads/2018/09/foto1.jpg);"></div>

any advice? thanks

Ad

Answer

Your syntax is wrong for getting attr data-src, use this

var bg_img = jQuery('.wp-show-posts-inner').attr('data-src');
jQuery('.wp-show-posts-inner').on('mouseover',function() {    
      jQuery('.home-banner .bg').css({'background-image': "url('"+bg_img+"')"});
});
jQuery('.wp-show-posts-inner').on('mouseleave',function() {    
      jQuery('.home-banner .bg').css({'background-image': "url()"});
});
.bg{height:100px;width:100px;}
.wp-show-posts-inner{height:100px;width:100px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="home-banner">
<div class="bg">

</div>
</div>
<div class="wp-show-posts-inner" data-src="http://maria138.coroleu.com/wp-content/uploads/2018/09/foto1.jpg">wp-show-posts-inner (Hover on me)</div>

Ad
source: stackoverflow.com
Ad