Click handlers can be assigned to elements easily with jQuery so when the element is clicked some particular action is run. This post looks at how to add a click handler to an element, explains how adding multiple click handlers will fire all of them, and then how to remove the click events.
Add a click handler
Adding a click handler to an element is as simple as the following example, where an alert box is opened when the user clicks the element with the ID "myelement":
$('#myelement').click(function(){ window.alert("You clicked me!"); });
Prevent browser from following anchor link
If you are assigning a click handler to an anchor tag, and do not want the browser to follow the link after the handler has run, add "return false;" at the end of the function:
$('#myelement').click(function(){ window.alert("You clicked me!"); return false; });
Adding multiple click handlers
More than one click handler can be assigned to an element with jQuery. When the element is clicked, all of the assigned event handlers will be triggered. So in the following example, if #myelement was clicked, an alert dialog would be displayed with the message "You clicked me!" followed by another alert dialog with the message "Another dialog box":
$('#myelement').click(function(){ window.alert("You clicked me!"); }); $('#myelement').click(function(){ window.alert("Another dialog box"); });
Removing click handlers
Use unbind(‘click’) to remove all assigned event handlers from an element. The following example will remove all handlers from the #myelement element:
$('#myelement').unbind('click');
Remove and add a click handler at the same time with method chaining
jQuery supports method chaining and you can remove all existing click handlers and assign a new click handler all at one go. The following example would clear all the click event handlers from #myelement and assign a new one:
$('#myelement').unbind('click').click(function(){ // do something here });
This is safe to use and will not cause any errors if no click events have already been bound to the element.