Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: What happens after binding an event more than once?

Thanks to jQuery, .on method binds a trigger to an element. I have a html like:

<div class='xyz'>click me</div>

and script like:

$('.xyz').on('click', function(){   alert('why?'); });
$('.xyz').on('click', function(){   alert('why?'); });

clicking on click me div triggers alert 2 times. It's ok, But:

  1. What exactly happens after binding second click trigger to the div?
  2. Is it a browser behavior or its done by jquery variables?

here is the fiddle: http://jsfiddle.net/hpmhpm/FCReC/

like image 755
hpaknia Avatar asked Oct 04 '22 05:10

hpaknia


People also ask

Does jQuery remove unbind events?

jQuery unbind() MethodThe unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs.

Why is this jQuery Ajax click event firing multiple times?

an Event will fire multiple time when it is registered multiple times (even if to the same handler).

Can you have multiple event listeners for the same event?

The addEventListener() methodYou can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.

What does jQuery bind do?

The bind() is an inbuilt method in jQuery which is used to attach one or more event handlers for selected element and this method specifies a function to run when event occurs. event: This is an event type which is passed to the selected elements.


1 Answers

What exactly happens after binding second click trigger to the div?

Jquery register's a new click event handler on .xyz, No matter, how many event handler's are already attached to your element

Is it a browser behavior or its done by jquery variables?

It's done by jquery


You can have as many event handler's you want on the same element, consider a scenario -

This is perfectly valid :

$('.xyz').on('click', function(){   // do some work });
$('.xyz').on('click', function(){   // do some other work });
like image 199
Mohammad Adil Avatar answered Oct 18 '22 10:10

Mohammad Adil