Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event capturing jQuery

I need to capture an event instead of letting it bubble. This is what I want:

<body>
   <div>
   </div>
</body>

From this sample code I have a click event bounded on the div and the body. I want the body event to be called first. How do I go about this?

like image 654
Toosick Avatar asked Jun 22 '13 09:06

Toosick


People also ask

What is stopPropagation jQuery?

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 jQuery handle event bubbling?

The concept of "bubbling up" is like if you have a child element with a click event and you don't want it to trigger the click event of the parent. You could use event. stopPropagation() . event.


2 Answers

Use event capturing instead:-

$("body").get(0).addEventListener("click", function(){}, true);

Check the last argument to "addEventListener" by default it is false and is in event bubbling mode. If set to true will work as capturing event.

For cross browser implementation.

var bodyEle = $("body").get(0);
if(bodyEle.addEventListener){
   bodyEle.addEventListener("click", function(){}, true);
}else if(bodyEle.attachEvent){
   document.attachEvent("onclick", function(){
       var event = window.event;
   });
}

IE8 and prior by default use event bubbling. So I attached the event on document instead of body, so you need to use event object to get the target object. For IE you need to be very tricky.

like image 163
pvnarula Avatar answered Sep 25 '22 06:09

pvnarula


I'd do it like this:

$("body").click(function (event) {
  // Do body action

  var target = $(event.target);
  if (target.is($("#myDiv"))) {
    // Do div action
  }
});
like image 37
Jonathan Avatar answered Sep 22 '22 06:09

Jonathan