View Full Version : Detect target on dynamically built events

03-28-2007, 02:18 AM
I do not know if there is a solution for this, but maybe somebody figured it out. Here is the problem:

I have to dynamically add an indeterminate images to a page.
For each image I add an event listener with the DOM function attachEvent.
The problem is that attachEvent (or its equivalent in Firefox) only allows the specification of a function, not its parameters. For example


When the event fires, there is no way to find out from which image it fired. The 'this' object will point to the window, not to the image from which it fired.

It looks like it is impossible to dynamically add events that would detect their target object.

Or is it possible?


03-28-2007, 03:16 AM
The this keyword will point to the object that fired the event in All browsers except IE. However, there is a better way:

function myfunction(e){
var e=e? e : window.event;
var el=e.target? e.target : e.srcElement;
the rest of your code goes here

When a function like that is fired by an event that is established with either attachEvent() or addEventListener(), the variable el will refer the the owner of the event.

03-29-2007, 10:13 PM
Thank you, John.
I love simple solutions like this.