Adriano Monecchi
Adriano Monecchi

Reputation: 1200

How to jQuery selectors, get an image's src and set it as a background-image of another element?

I'm trying to make this work with the following scenario:

My goal is to get the first image's src from the html structure bellow and then set its src value as the background-image: of another element which exists in the DOM.

The HTML output, dynamically loaded.

I've set up the Instafeed jQuery plugin in a way it outputs the following html structure: Images are dynamically loaded through Instagram API.

I want to grab the image src from the first image bellow...

<div id="instafeed">
<div class="col-xs-4">
 <a href="#" target="_blank" class="thumbnail fa-eye fa">
  <img class="dynamic-image" src="https://scontent.cdninstagram.com/hphotos-xpa1/t51.2885-15/e15/10375586_312675495555582_308260980_n.jpg">
 </a>
</div>

<div class="col-xs-4">
 <a href="#" target="_blank" class="thumbnail fa-eye fa">
  <img class="dynamic-image" src="https://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/e15/10454019_1429094704028916_1903084125_n.jpg">
 </a>
</div>

<div class="col-xs-4">
 <a href="#" target="_blank" class="thumbnail fa-eye fa">
  <img class="dynamic-image" src="https://scontent.cdninstagram.com/hphotos-xpf1/t51.2885-15/e15/1530818_682625665122870_298851871_n.jpg">
 </a>
</div>
</div>

...And place it as the url of the following target element .bgcover:

<div class="masthead bgcover" style="background-image: url('https://distilleryimage11-a.akamaihd.net/fdc05880f98511e2af2c22000a9e510c_7.jpg');"></div>

jQuery

The code bellow works, however, it gets the img src of one of the images in the html out and not the first one...

$( window ).load(function() {
// For each image with the class .dynamic-image on the page
$(".dynamic-image").each(function() {
// Grab the image
var image_source = $(this).attr('src');

// Set the background
$(".bgcover").css("background-image",'url('+image_source+')');

 });
});

By reading the jQuery's :eq() Selector documentation, I'm now trying to learn how to use the selectors, but I'm pretty new to JS/jQuery, so I'd really appreciate any hints about making it work the right way.

Upvotes: 0

Views: 2202

Answers (1)

Bala
Bala

Reputation: 706

The .each() function in jquery is like a loop. It will run loop through for every match. So, in your above code, ideally it is going to pick the last img tag and set its image as the background.

Instead if you used .first() function it would return the first element that it matches. This is the implementation that would work for you.

$(window).load(function () {
    // For each image with the class .dynamic-image on the page

    // Grab the image
    var image_source = $(".dynamic-image").first().attr('src');
    image_source = "url('" + image_source + "')";
    // Set the background
    $(".bgcover").css("background-image", image_source);

});

Hope this helps.

Upvotes: 1

Related Questions