Assign and remove a click handler from an element with jQuery
Posted December 1st, 2009 in Javascript
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.
Related posts:
- Disable a link from going to the href URL with jQuery (Monday, September 12th 2011)
- jQuery: Mouse co-ordinates within the element when mouseover or click an element (Wednesday, October 28th 2009)
- Get the mouse co-ordinates with jQuery when an element is clicked (Friday, October 9th 2009)
- Find the index of the element that was clicked with jQuery (Tuesday, May 19th 2009)
- Adding, removing and checking if an element has a CSS class with jQuery (Tuesday, December 16th 2008)
- How to check and uncheck a checkbox with jQuery (Friday, November 14th 2008)

Comments
blog comments powered by Disqus