You need to handle the click event at the document level. In the event object, you have the target property, the innermost DOM element that was clicked. With this, you test yourself and approach the parents to the document element if one of them is your observed element.
See an example in jsFiddle
document.addEventListener("click", function (e) { var level = 0; for (var element = e.target; element; element = element.parentNode) { if (element.id === 'x') { document.getElementById("out").innerHTML = (level ? "inner " : "") + "x clicked"; return; } level++; } document.getElementById("out").innerHTML = "not x clicked"; });
As always, this is not cross browser compatible due to addEventListener / attachEvent, but it works as follows.
A child is pushed, if not event.target, but one of its parents is an observable (I just count the level for this). You may also have boolean var if the element is found or not, so as not to return a handler from the for clause. My example limits the fact that the handler ends only when nothing matches.
When adding cross-browser compatibility, I usually do it like this:
var addEvent = function (element, eventName, fn, useCapture) { if (element.addEventListener) { element.addEventListener(eventName, fn, useCapture); } else if (element.attachEvent) { element.attachEvent(eventName, function (e) { fn.apply(element, arguments); }, useCapture); } };
This is cross-browser compatible code for attaching a listener / event handler, including rewriting this in IE as an element, like jQuery for event handlers. There are many arguments to keep in mind a few jQuery bits;)
metadings Jan 07 '13 at 1:28 2013-01-07 01:28
source share