The click Event
React when a user clicks an element.
Syntax
$(selector).on("click", handler);The click event is the most common interaction. jQuery lets you attach a handler function that runs on each click.
Inside the handler, $(this) refers to the element that was clicked, wrapped as a jQuery object.
Example
Loading editor…
Press Run to see the result.
When to use it
- A modal dialog opens when the user clicks a "View details" button, using .click() to add the open class.
- A delete button triggers a confirmation prompt and an AJAX call via a .click() handler.
- A colour-picker swatch applies a theme to the page by reading the clicked element's data attribute on click.
More examples
Toggle visibility on click
.click() attaches a handler; .toggle() alternates between visible and hidden on each click.
<button id="toggle">Show / Hide</button>
<p id="content">Here is the content.</p>
<script>
$(function () {
$("#toggle").click(function () {
$("#content").toggle();
});
});
</script>Count button clicks
A variable tracks clicks and .text() updates the display every time the button is pressed.
<button id="counter">Click me</button>
<p>Clicks: <span id="num">0</span></p>
<script>
$(function () {
var count = 0;
$("#counter").click(function () {
count++;
$("#num").text(count);
});
});
</script>Confirm then delete a list item
Each .del button removes its parent <li> only after the user confirms, using .closest() to walk up the tree.
<ul id="list">
<li>Item A <button class="del">x</button></li>
<li>Item B <button class="del">x</button></li>
</ul>
<script>
$(function () {
$(".del").click(function () {
if (confirm("Delete this item?")) {
$(this).closest("li").remove();
}
});
});
</script>
Discussion