Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to check if bubble triggered the click?

Clicking on elements in jQuery causes bubble up to body. If we have a click handler binded to body that shows an alert, then clicking on any element will bubble up to body and trigger the alert. My Question is, is there any way to know if the body alert was triggered as a result of direct click to body, or was the click triggered because of a bubble up to body.

like image 603
Pinkie Avatar asked May 19 '11 18:05

Pinkie


People also ask

What is the difference between event capturing and bubbling?

With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. With capturing, the event is first captured by the outermost element and propagated to the inner elements.

In what order does event flow occur after a click '?

That is: for a click on <td> the event first goes through the ancestors chain down to the element (capturing phase), then it reaches the target and triggers there (target phase), and then it goes up (bubbling phase), calling handlers on its way.

How do you stop event bubbling?

The event. stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.

How does event bubbling work?

Event bubbling is a type of 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 initialized).


2 Answers

Compare event.target to this. this is always the event where the handler is bound; event.target is always the element where the event originated.

$(document.body).click(function(event) {     if (event.target == this) {         // event was triggered on the body     } }); 

In the case of elements you know to be unique in a document (basically, just body) you can also check the nodeName of this:

$(document.body).click(function(event) {     if (event.target.nodeName.toLowerCase() === 'body') {         // event was triggered on the body     } }); 

You have to do toLowerCase() because the case of nodeName is inconsistent across browsers.

One last option is to compare to an ID if your element has one, because these also have to be unique:

$('#foo').click(function(event) {     if (event.target.id === 'foo') {         // event was triggered on #foo     } }); 
like image 80
lonesomeday Avatar answered Sep 29 '22 09:09

lonesomeday


You can check what was clicked with event.target:

$(something).click(function(e){     alert(e.target) }) 
like image 25
Naftali Avatar answered Sep 29 '22 09:09

Naftali