Mary624
Mary624

Reputation: 75

Get image src using JQuery from dynamically loaded images

I have some php code which creates html that displays images by pulling their paths from a database:

        $primephoto = ~some path from a database~;
        echo '  
            <div class="widget_photo">
                <img src="'.$primephoto.'">
            </div>';

I am trying to get the source of the image I click on using the following code:

        $(".widget_photo img").click(function(){ 
            var images = $('.widget_photo img').attr('src');
            alert(images);  
        });

But it returns the source of just the first image always.

I think whats going on is that the php code is rendering a bunch of html div's all with the class name "widget_photo", and the JQuery just looks at the first one, grabs the image src and returns that.

But I need the source of the specific image that is being clicked on.

Any suggestions would be very appreciated!

Upvotes: 0

Views: 1529

Answers (1)

dfsq
dfsq

Reputation: 193261

You need to get src of the current this image:

$(".widget_photo img").click(function(){ 
    var images = $(this).attr('src');
    alert(images);  
});

Upvotes: 3

Related Questions