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:
here is the fiddle: http://jsfiddle.net/hpmhpm/FCReC/
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.
an Event will fire multiple time when it is registered multiple times (even if to the same handler).
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.
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.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With