Given a simplified document like this:
<div id="outerDiv">
<div id="innerDiv">
<input id="theInput" />
</div>
</div>
If I were to click on #theInput
, the click event would bubble up to #innerDiv
and then #outerDiv
. What I'd like to do would be to put a handler on #outerDiv
to listen for those clicks, and then inspect the 'bubble-chain' to see which elements have previously received this same click event.
So, for example, clicking on #theInput
the handler in #outerDiv
would give me [#outerDiv, #innerDiv, #theInput]
. If I were to click outside of #theInput
, but still inside #innerDiv
then the result would be [#outerDiv, #innerDiv]
Just to clarify, the actual document is not as simple as this, and there could be any number of children or siblings at each level. Also, when I refer to #theInput
, I'm referring to the element itself, that is, I'm not looking for an array of IDs. Lastly, given that there could be any number of elements, I'd like to avoid adding extra handlers to intermediate elements.
jQuery is welcome in my house.
Seems like:
function myHandler(ev) {
var $bubbleParents = $(ev.target).parents();
// ...
}
is all you need, esp. if you're using jQuery and your event handlers will have this
bound to the element relevant to the handler code. The list of parents from the target will tell you all the elements that the event can possibly bubble to, and your this
reference will be one of the elements in that list. (I think the list of parents is in "inner-to-outer" order, but I'd have to check in a fiddle.) Thus you can tell which elements have already been "visited" and which haven't.