Live click fires several times

Practice




live click fires several times

the code


$('#sendr').live('click', function() {

});


even after replacing it with

$('#sendr').bind('click', function() { });

$('#sendr').click( function() { });

$( "#sendr" ).on( "click", "a", function( e ) {} );

it still fires twice on a single click, I can't work out why

actually the live methods aren't supported in the newer versions any more, use ON instead,

and your problem is probably that the handler is attached several times
if your jquery code is in a separate file, check how many times it's included, most likely twice

yes, thanks, it really was included twice

could you write in more detail how to replace live with on

// Bind attaches the handler directly to the element (when it is present in the DOM). When the element is removed, the handler is removed too
$( "#sendr li a" ).on( "click", function( e ) {} ); replaces
$( "#sendr li a" ).bind( "click", function( e ) {} );



// Live attaches the handler to the document and uses delegation (event bubbling). It lets you create a handler before the element appears in the DOM. When the element is removed the handler isn't removed, it simply stops firing. If you insert an element matching the selector into the DOM again, the handler will fire again.
It is used even for elements that will be added in the future, and the attached method will fire for them too


$( document ).on( "click", "#sendr li a", function( e ) {} ); replaces
$( "#sendr li a" ).live( "click", function( e ) {} );


// delegate — exactly like live, uses delegation, only the node the handler is attached to is specified explicitly.

$( "#sendr" ).on( "click", "li a", function( e ) {} ); replaces
$( "#sendr" ).delegate( "li a", "click", function( e ) {} );



when you assign live, the event is actually attached to window.document, and whenever any click on the document occurs it checks "was the click on the type of element we need or not"

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Scripting client side JavaScript, jqvery, BackBone"

Terms: Scripting client side JavaScript, jqvery, BackBone