aronkerr
aronkerr

Reputation: 314

jQuery binding events within an event listener

I have a link with a click event listener bound to it. On click it attaches a click event listener to the document, this time the event is namespaced so that I can easily remove it. Upon attaching the second event it is immediately fired. Why is this occuring? My best guess is that the event is still bubbling up the dom tree when the new event is attached to the document. Because of this it triggers both events. See the following JSFiddle.

HTML

<a href="#" id="example">Click Me</a>

Javascript

$('#example').on('click', function(e) {
    $(document).on('click.example', function(e) {
        alert('example event triggered');
    });
});

What I am trying to accomplish is that on clicking a button I insert a dom element. When it is inserted I want to attach an event listener to the document that when triggered checks the event target in order to detect if any click events occur outside of the inserted element. If the target is within it it should do nothing. If the target is anywhere outside of the element it should hide the element.

Upvotes: 2

Views: 3697

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

It is because of event propagation

$('#example').on('click', function(e) {
  $(document).on('click.example', function(e) {
    alert('example event triggered');
  });
  e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="example">Click Me</a>

You are registering the handler when the event is still in the anchor element, and the event is bound to the document object which is a ancestor of the current element. So now when the event is eventually propagated and reaches the document object it will find the click handler bound to it and will trigger it.

Note: You should not just add new handlers in every click... hopefully you have taken care of it

Upvotes: 3

Related Questions