Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the elements which an event has bubbled through

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.

like image 555
nickf Avatar asked Mar 24 '11 14:03

nickf


People also ask

What is events and explain event bubbling with an example?

Event bubbling is a method of event propagation in the HTML DOM API when an event is in an element inside another element, and both elements have registered a handle to that event. It is a process that starts with the element that triggered the event and then bubbles up to the containing elements in the hierarchy.

What is meant by event bubbling?

Event bubbling is a type of DOM event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element or document object (Provided the handler is ...

What is bubbling and capturing?

Capturing phase – the event goes down to the element. Target phase – the event reached the target element. Bubbling phase – the event bubbles up from the element.


1 Answers

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.

like image 66
Pointy Avatar answered Oct 14 '22 03:10

Pointy