The **click** event is by far the most used interaction on the web. It triggers an action whenever a user clicks an element with their mouse or taps it on a touchscreen. jQuery provides dedicated methods for both single and double clicks.
The click() method attaches an event handler function to an HTML element.
This function fires when the user clicks on that element.
$(selector).click(function() {
// Code to run on click
});
While a regular click is common, sometimes you may want to differentiate between a single and a double click.
Fires on a single mouse click. Best for buttons, links, and navigation.
$("p").click(function() {
$(this).hide();
});
Fires only after a rapid double click. Good for advanced UI features like "editing" a line.
$("p").dblclick(function() {
$(this).fadeOut();
});
Below is how you would use these methods in a real project to change an element's look or behavior.
<button id="btn1">Single Click Me</button>
<button id="btn2">Double Click Me</button>
<p id="demo">Watch my color change!</p>
<script>
$(document).ready(function() {
// Single click action
$("#btn1").click(function() {
$("#demo").css("color", "red");
});
// Double click action
$("#btn2").dblclick(function() {
$("#demo").css("color", "blue");
});
});
</script>
dblclick() on links or primary buttons
as it can confuse users who expect an immediate response from a single click.
The $(this) keyword is particularly powerful with clicks because it allows
you to target the exact element that was clicked, even if multiple elements share the
same class.
$("li").click(function() {
// Only the SPECIFIC list item clicked will turn green
$(this).css("color", "green");
});
In modern jQuery development, you might see the on() method used instead of
click(). They often do the same thing, but on() is better for
elements added to the page dynamically.
| Short Notation | Standard Notation (Modern) |
|---|---|
$("#btn").click(function() { ... }); |
$("#btn").on("click", function() { ... }); |