Jon
Jon

Reputation: 976

How do you retrieve the image source of an image that the user has clicked on? (jQuery)

I am trying to retrieve the image source of an image that the user has clicked on. This is what I have and it doesn't seem to be working:

var imgSrc = getSrc(image)

    function getSrc(image) {
        $('img').each(function() {
            $(this).click(function() {
                $(this).attr('src')
            }); //end click
        }); //end each  
    } //end getSrc

Upvotes: 0

Views: 63

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

$('img').click(function() {
    alert( $(this).attr('src') ); // or this.src
 }); 

You don't need any loop. Above code will work just fine, I think.

Full code

function getSrc(image) {
   var src;
   $('img').click(function() {
     src = $(this).attr('src'); // or this.src
   }); 
   return src;
}

Note

In your question you don't use image arguments in code. I'm not sure why you're using this. If you want to use get src of that image you passed via arguments then you can try:

$(image).attr('src');

Upvotes: 7

xcopy
xcopy

Reputation: 2288

You are not returning anything from the function. Also, you do not need the .each() call as you know the image that has been clicked:

var imgSrc = '';

$(document).ready(function () {
    $('img').click(function () {
        imgSrc = $(this).attr('src');
    });
});

Upvotes: 0

Related Questions