Multiple ways to attach a click event to an element
Shiv Prakash April 28, 2024
- JQUERY SHORTS
A click event can be attached to an element in various ways. Below are a few different options:
#1. Using .click() method
$("#elementId").click(function() {
// Custom code here
});
- Specifically designed to attach a click event listener.
- A shortcut for .on(“click”, function() { … }).
#2. Using .on() method for direct elements
$(".elementClass").on("click", function() {
// Custom code here
});
- .on(): This method is more versatile.
- It can be used to attach various event listeners to an element like mouseenter, mouseleave, or submit.
#3. Using .on() method for dynamic or future elements:
$(document).on("click", "#elementId", function() {
//Custom code here
});
- I hope you enjoyed this short. If you find it useful, leave us a comment. I would love to hear your thoughts and suggestions to make it better. Also, you can connect with me on LinkedIn.