Tim Aych
Tim Aych

Reputation: 1365

Getting SRC of image elements upon clicking on them

Trying to attach a click event handler to each image and then alert the SRC when the image is clicked.

HTML:

<img src="http://www.lorempixel.com/100/200">

<img src="http://www.lorempixel.com/200/200">

<img src="http://www.lorempixel.com/400/200">

<img src="http://www.lorempixel.com/200/200">

JavaScript:

var pics = document.getElementsByTagName('IMG');

for (x=0; x < pics.length; x++) {
    pics[x].addEventListener('click', function(){
        alert(pics[x].getAttribute('src'));
    }, false);
}

I know it's something simple I'm messing up, but I can't figure it out.

Upvotes: 0

Views: 25

Answers (1)

Niflhel
Niflhel

Reputation: 663

When you add the event listener, you have to refer to the clicked element instead of your loop element.
So it will not be pics[x] but this (referring to the clicked element) instead.

Here is a jsFiddle:
http://jsfiddle.net/Hbc4M/

var pics = document.getElementsByTagName('IMG');

for ( x=0; x < pics.length; x++ ) {
    pics[x].addEventListener('click', function(){
        alert(this.getAttribute('src'));
    }, false);
}

Upvotes: 1

Related Questions