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 click
event 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 with onclick
.
But the event also "bubbles up" to the parent, and it's caught by the onclick
function 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 document
object itself, or maybe the document.body
element if you still want to use onclick
(which is deprecated).
The event object is passed to the onclick function and it contains the original element that fired the event:
document.body.onclick = function(e) {
var tgt = e.target || e.srcElement;
if (tgt.tagName === "IMG")
alert(tgt.src);
}
(The e.target || e.srcElement
part is because in IE<9 the target
property is called srcElement
.) 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 click
event listener in the traditional way, I'd strongly recommend to use something more modern like the addEventListener
method, which lets you add multiple event listeners on the same element for the same event type:
document.body.addEventListener("click", function(e) {
...
});
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.