Toosick
Toosick

Reputation: 470

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?

Upvotes: 20

Views: 38420

Answers (3)

Jordan Weitz
Jordan Weitz

Reputation: 48

More generally than @pvnarula's answer:

var global_handler = function(name, handler) {
    var bodyEle = $("body").get(0);
    if(bodyEle.addEventListener) {
        bodyEle.addEventListener(name, handler, true);
    } else if(bodyEle.attachEvent) {
        handler = function(){
            var event = window.event;
            handler(event)
        };
        document.attachEvent("on" + name, handler)
    }
    return handler
}
var global_handler_off = function(name, handler) {
    var bodyEle = $("body").get(0);
    if(bodyEle.removeEventListener) {
       bodyEle.removeEventListener(name, handler, true);
    } else if(bodyEle.detachEvent) {
       document.detachEvent("on" + name, handler);
    }
}

Then to use:

shield_handler = global_handler("click", function(ev) {
    console.log("poof")
})

// disable
global_handler_off("click", shield_handler)
shield_handler = null;

Upvotes: 1

Jonathan
Jonathan

Reputation: 9151

I'd do it like this:

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

  var target = $(event.target);
  if (target.is($("#myDiv"))) {
    // Do div action
  }
});

Upvotes: 3

pvnarula
pvnarula

Reputation: 2821

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.

Upvotes: 42

Related Questions