cameron
cameron

Reputation: 420

jQuery find image in div and save src as variable to use as css background image

I have several divs on a page that have 1 randomly generated image in each div. I need to be able to find the image source value for each of those images and save them to a variable. I then need to assign those images as background css to other elements on the page. Example:

<div class="wrapper div1"><img src="/image1.png" /></div>
<div class="wrapper div2"><img src="/image2.png" /></div>
<div class="wrapper div3"><img src="/image3.png" /></div>

<div class="background div1"></div>
<div class="background div2"></div>
<div class="background div3"></div>
$(function() {
    var div1Image = $('.wrapper.div1').find('img').attr('src');
    var div2Image = $('.wrapper.div2').find('img').attr('src');
    var div3Image = $('.wrapper.div3').find('img').attr('src');
    $('.background.div1').css('background-image', "url(' + div1Image + ') no-repeat");
    $('.background.div2').css('background-image', "url(' + div2Image + ') no-repeat");
    $('.background.div3').css('background-image', "url(' + div3Image + ') no-repeat");
});     

This code does nothing though. Am I going about this all wrong? Any thoughts as to what I am missing here? Thanks

Upvotes: 1

Views: 2795

Answers (1)

empiric
empiric

Reputation: 7878

The css-property background-image does not support no-repeat. Furhtermore your quotes are mismatching.

The following should work:

$(function() {
  var div1Image = $('.wrapper.div1').find('img').attr('src');
  var div2Image = $('.wrapper.div2').find('img').attr('src');
  var div3Image = $('.wrapper.div3').find('img').attr('src');
  $('.background.div1').css('background-image', 'url(' + div1Image + ')');
  $('.background.div2').css('background-image', 'url(' + div2Image + ')');
  $('.background.div3').css('background-image', 'url(' + div3Image + ')');
});

Or use background instead of background-image

Demo


This could be a little improvment to your script:

$(function() {

  $('.wrapper').find('img').each(function(index){
        var src = $(this).attr('src');
      $('.background').eq(index).css('background', 'url(' + src + ') no-repeat');
  });

});

This is independent from the number of elements.

Demo2

Upvotes: 6

Related Questions