2

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.

1 Answer 1

3

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/

Sign up to request clarification or add additional context in comments.

1 Comment

brilliant - I knew it was something to do with 'this' just haven't quite got my head around it yet! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.