Detect element’s click event with JavaScript/jQuery
This post will discuss how to detect click events on an element using JavaScript and jQuery.
There are several ways to listen to click events with JavaScript and jQuery.
1. Using jQuery
With jQuery, you can use the .on() method to attach event handlers to one or more elements. The following code demonstrates its usage by attaching a click event handler to a submit button.
JS
|
1 2 3 4 5 6 |
$(document).ready(function() { $("#submit").on('click', function(event) { alert("Submit button is clicked!"); event.preventDefault(); }); }); |
HTML
|
1 |
<button id="submit">Submit</button> |
There is a shorthand method in jQuery for the .click() event to attach event handlers.
JS
|
1 2 3 4 5 6 |
$(document).ready(function(event) { $("#submit").click(function() { alert("Submit button is clicked!"); event.preventDefault(); }); }); |
HTML
|
1 |
<button id="submit">Submit</button> |
2. Using JavaScript
With pure JavaScript, you can use the EventTarget.addEventListener() method to bind to click event of an element.
JS
|
1 2 3 4 5 |
document.getElementById("submit") .addEventListener("click", function(event) { alert("Submit button is clicked!"); event.preventDefault(); }); |
HTML
|
1 |
<button id="submit">Submit</button> |
Alternatively, you can use the onclick handler for specifying an event listener to receive click events.
JS
|
1 2 3 4 |
document.getElementById("submit").onclick = function(event) { alert("Submit button is clicked!"); event.preventDefault(); } |
HTML
|
1 |
<button id="submit">Submit</button> |
That’s all about detecting an element’s click event in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)