Identify the elements through which the event occurred.

Given a simplified document:

<div id="outerDiv"> <div id="innerDiv"> <input id="theInput" /> </div> </div> 

If I clicked on #theInput , the click event would move to #innerDiv and then #outerDiv . What I would like to do is place a handler on #outerDiv to listen for these clicks, and then check the bubble chain to see which items previously received the same click event.

So, for example, by clicking #theInput , the handler in #outerDiv will give me [#outerDiv, #innerDiv, #theInput] . If I pressed the #theInput button, but still inside #innerDiv , then the result would be [#outerDiv, #innerDiv]

To clarify, the actual document is not as simple as this, and at each level there can be any number of children or brothers and sisters. Also, when I refer to #theInput , I mean the element itself, that is, I am not looking for an array of identifiers. Finally, given that there can be any number of elements, I would like to avoid adding additional handlers to the intermediate elements.

jQuery is welcome in my house.

+4
source share
3 answers

It seems that:

 function myHandler(ev) { var $bubbleParents = $(ev.target).parents(); // ... } 

- that’s all you need, especially. if you use jQuery and your event handlers will have this bound to an element related to the handler code. The list of parents from the target group will tell you about all the elements that the event may happen, and your link this will be one of the elements in this list. (I think the parent list is in an "internal-external" order, but I will need to check the fiddle.) This way you can determine which items are already "visited" and which are not.

+7
source

With an event object, use the target to find out the click element. From there, you can use the parents () function in jQuery to find all the parents in the chain.

 var parents; handler = function(e){ // specifying the limit node in parents parents = $(e.target).parents("#outerDiv"); }; 
+1
source
 $('outerDiv').bind('click', function(e) { var current = e.target; var arrayClicked = new Array(); arrayClicked[] = current; function test() { if(current.parent() == $('.outerDiv')) { return arrayClicked; } else { arrayClicked[] = current; current = current.parent(); test(); } } var yourdivs = test(); }); 
0
source

Source: https://habr.com/ru/post/1345094/


All Articles