Wednesday 20 July 2011

Triggering an event handler only for the first occurance of an event using jQuery one()

This method is identical to .bind(), except that the handler is unbound after its first invocation. For example:

$("#bob").one("click", function() {
alert("This will be displayed only once.");
});



After the code is executed, a click on the element with ID "bob" will display the alert. Subsequent clicks will do nothing. This code is equivalent to:

$("#bob").bind("click", function( event ) {
alert("This will be displayed only once.");
$(this).unbind( event );
});



In other words, explicitly calling .unbind() from within a regularly-bound handler has exactly the same effect.

No comments:

Post a Comment