1

I need to do in pure JavaScript what I easily do in jQuery:

$('document').click(function(e){
   e.preventDefault();
});

In some manner, jQuery guarantees that my event runs first, thus preventing every other registered click event will not be executed.

When I'm trying it with JavaScript

document.addEventListener('click', function(e){
   e.preventDefault();
   e.stopPropagation();
}, 1);

My event is always running last, so I can't prevent the others.
Is there anyway to guarantee that the event I'm added, will be added to the top of the stack, so is executed first?

3
  • No, you can't do that. Events are un-ordered, deal with it otherwise. Commented Jan 20, 2012 at 11:11
  • Sorry, m8, but if jQuery does that, there must be a way. I will try to reverse engineer it but it would be easier if someone had a direct answer. Commented Jan 20, 2012 at 11:29
  • Of course you can do it by writing your own event system. That's what jQuery does, it has it's own event system. Commented Jan 20, 2012 at 11:45

1 Answer 1

1

That is not correct. event.preventDefault will not prevent any other registered handler from firing, it'll just prevent the "default" behavior (for instance, for an anchor).

event.stopPropagation will prevent the event from further bubbling up the DOM tree, so this is probably a more accurate description for that. However, it makes no difference whether you bind an event with addEventListener or jQuery (since it'll use the same function underneath).

Are you sure you're binding the event at the same position ?

Sign up to request clarification or add additional context in comments.

2 Comments

i am using a library that, for reasons, i need to load before my javascript and, i can't tamper the code. So, their event(with an anonymous function) is added to the document before my event. How can i stop it from running?
event.stopImmediatePropagation() will stop the event from bubbling and not invoke any other listeners for the current stage. It does make a big difference whether you use jQUery or addEventListener because jQuery emulates their own event system completely and only lightly hooks into the DOM. jQuery's event listeners are ordered because they add one new listener that invokes all listeners in order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.