stevenvh
stevenvh

Reputation: 3139

Javascript: how do I refer to the object which owns the event handler?

I have a page with image thumbnails, and each thumbnail has an onclick event.

<a href='javascript:void(0)' onclick='getInfo();'>
  <img src='album/123.jpg' width='200' height='150' alt='' />
</a>     
<a href='javascript:void(0)' onclick='getInfo();'>
  <img src='album/456.jpg' width='240' height='320' alt='' />
</a>  

In the event handler getInfo() I want to get info of the image I clicked, like the source filename or the height. How can I do this? (I was hoping to use this, but that seems to refer to the window, not the <a> tag.)
I'm not using jquery (yet), so I would appreciate a pure javascript answer.

Upvotes: 2

Views: 60

Answers (3)

user2587132
user2587132

Reputation:

http://jsfiddle.net/Xrzs3/

<a href='#'>
  <img src='http://www.vectortemplates.com/raster/batman-logo-big.gif'
       width='40px' height='40px' />
</a>

onload

var a=document.getElementsByTagName("a");

for(var i=0;i<a.length;i++){
   a[i].addEventListener("click", function(e){
   var img=e.target;
   var src=img.src;
   alert("image source = "+src);
   }, false);
}

Upvotes: 0

Kevin Murani
Kevin Murani

Reputation: 186

Try this:

function getInfo() { 
        var owner = (window.event.target) ? window.event.target  : window.event.srcElement;
        // rest of your code
    }

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148524

Just do this :

onclick='getInfo(this);'>...

then you can get the reference in the method itself

Or you can do this :

onclick='getInfo(event);' // IE dont send I think - but chrome do.

and in the function you can get the Target .

via event :

function getInfo (evt)
{
 evt.target...
}

via this :

function getInfo (that)
{
   do something with that....
}

Upvotes: 1

Related Questions