I’m a JS newbie – still learning. I’m looking for a solution similar to this example
for displaying the source link of an image in an alert using onclick. However, I want to apply it to any image on the page, and there are no ID’s on any of the images. Perhaps this is an application of the mysterious ‘this’? Can anyone help me? Thanks!
No, this has to do with delegate event listeners, and the way events spread across the DOM.
When you click on an element in the page, a
clickevent is generated. For what it matters to your purposes, this event is fired on the element, and it’s caught by the function you define withonclick.But the event also “bubbles up” to the parent, and it’s caught by the
onclickfunction defined there, if any. And then to the parent of the parent, and so on.What you have to do, now, is to catch the event on the root element, which is the
documentobject itself, or maybe thedocument.bodyelement if you still want to useonclick(which is deprecated).The event object is passed to the onclick function and it contains the original element that fired the event:
(The
e.target || e.srcElementpart is because in IE<9 thetargetproperty is calledsrcElement.) That’s the way you define a delegate event listener. It’s not defined on the<img>elements, as you can see, but on their common ancestor.But since you can define just one
clickevent listener in the traditional way, I’d strongly recommend to use something more modern like theaddEventListenermethod, which lets you add multiple event listeners on the same element for the same event type:In Internet Explorer <9 you’ll have to use
attachEvent, which is quite similar but not the same. For a cross-browser solution, use a common JS framework like jQuery, or Prototype, or whatever.