0

I have a click event on the body of my document:

$("body").on('click.findElem', function(e) {                 
            e.stopPropagation();  
            e.preventDefault();    
            self.hinter(e.target);            
            return false;
        });

It basically catches the clicked target and does something to it. However, there are some targets that already have a click event on them, and they prevent my click from being executed at all. How do I overcome that issue? I tried unbinding it, but the click doesn't even work at all to actually execute the unbinding.

nainy
  • 520
  • 1
  • 4
  • 21

3 Answers3

1

e.stopImmediatePropagation() does the job, but only if your handler executes before whatever other handler exists.

Unfortunately there is no way to insert your own handler in the first position - but you can use this nasty hack if the other handlers were bound using jQuery, too: How do you force your javascript event to run first, regardless of the order in which the events were added?

If you really need this you might want to bind an event handler in capture mode using the native DOM API: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener

Capture handlers are triggered before bubble handlers (which are used by jQuery and most other scripts) so that way you have very high chance to execute your handler first.

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
0

try this and see demo

$( "body" ).on( "click", ".clickme:not(.clicked)", function( event ) {
    $(this).addClass('clicked');
    alert('here');
});
Harish Singh
  • 3,359
  • 5
  • 24
  • 39
0

i tend to not use on and stick with the bind/unbind combo. i have some pages that reload partial content and then has to rebind the events. i tipically do something like this

$(".theobjectsiwant").unbind("click").bind("click", function() {
    alert('hi there');
});

If you want/have to stick with the on() function, you shouldn't mix on() with unbind() and try a similar approach with .off("click").on("click")

Check here for a sample http://api.jquery.com/off/

Faber75
  • 106
  • 8