Sam Skirrow
Sam Skirrow

Reputation: 3697

jQuery Grab attribute for an item in an array

I have a set of divs that are dynamically created via php, the divs have an attribute called 'data-image-url' which holds the image url for a pop-up gallery. When I click the div, an overlay pops up along with a gallery of 3 images for that div (similar to a lightbox).

I have created the overlay and the divs to contain the related gallery images (there will only ever be 3). However, I can't figure out how to grab the value from the attribute 'data-image-url' and make that as the background image for the div.

Here is my current working, the outputted php as html is as follows:

<div id="overlay"></div>

<div class="blank christmas">
    <div data-image-url="http://www.samskirrow.com/client-kateguest/wp-content/uploads/2013/09/Christmas.jpg" class="gallery">
        <img src="img/grey.png" class="lazy" data-original="http://www.samskirrow.com/client-kateguest/wp-content/uploads/2013/09/Christmas-135x190.jpg" alt="" />
    </div>
 </div>

<div class="blank christmas">
    <div data-image-url="http://www.samskirrow.com/client-kateguest/wp-content/uploads/2013/09/Joy.jpg" class="gallery">
        <img src="img/grey.png" class="lazy" data-original="http://www.samskirrow.com/client-kateguest/wp-content/uploads/2013/09/Joy-135x190.jpg" alt="" />
    </div>
 </div>

so As you can see, the data-image-url is what I'm trying to grab here to use as the background image of my div in the pop-up.

Here is my jQuery so far:

$('.gallery').click(function() {
$('#overlay').fadeIn().append('<div class="main_image"></div>');
});

$main_img_url = $('.gallery').attr('data-image-url').html();
$('.main_image').css("background-image", $main_img_url);

And a JsFiddle to show my workings: http://jsfiddle.net/9d9sz/1/

I think the issue is that the outputted html has several "data-image-url" attributes (as there are several images), but I don't know how to target the specific one for the image I clicked on.

Upvotes: 2

Views: 348

Answers (1)

ʞɹᴉʞ ǝʌɐp
ʞɹᴉʞ ǝʌɐp

Reputation: 5650

Try using

$('.gallery').click(function() {
$('#overlay').fadeIn().append('<div class="main_image"></div>');
    $main_img_url = $(this).attr('data-image-url');
    $('.main_image').css("background-image", "url('" + $main_img_url + "')")
});

DEMO http://jsfiddle.net/9d9sz/2/

Upvotes: 3

Related Questions