.click()

Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

.click(function(eventObjectEvent))🡢 jQuery

function(eventObjectEvent) FunctionA function to execute each time the event is triggered.

.click(eventData, function(eventObjectEvent))🡢 jQuery

eventData AnythingAn object containing data that will be passed to the event handler.
function(eventObjectEvent) FunctionA function to execute each time the event is triggered.

.click()🡢 jQuery

This method is a shortcut for .on( "click", handler ) in the first two variations, and .trigger( "click" ) in the third. The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event. For example, consider the HTML:

<div id="target">Click here</div>
<div id="other">Trigger the handler</div>
Figure 1 - Illustration of the rendered HTML

The event handler can be bound to any <div>:

$("#target").click(function () {
  alert("Handler for .click() called.");
});

Now if we click on this element, the alert is displayed:

Handler for .click() called.

We can also trigger the event when a different element is clicked:

$("#other").click(function () {
  $("#target").click();
});

After this code executes, clicking on Trigger the handler will also alert the message.

The click event is only triggered after this exact series of events:

  • The mouse button is depressed while the pointer is inside the element.
  • The mouse button is released while the pointer is inside the element.

This is usually the desired sequence before taking an action. If this is not required, the mousedown or mouseup event may be more suitable.

Hide paragraphs on a page when they are clicked:

JS
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
CSS
p {
  color: red;
  margin: 5px;
  cursor: pointer;
}
p:hover {
  background: yellow;
}
HTML
$("p").click(function () {
  $(this).slideUp();
});
DEMO

Trigger the click event on all of the paragraphs on the page:

HTML
$("p").click();
DEMO

Looking for a Web Developer?

👋

Hi! I'm Basti, author of this site. If you are looking for a web developer with 15+ years of experience, holla at me!

Be it the good 'ol jQuery, vanilla JS or modern frameworks like Vue and Svelte, front- or backend, I can help you.

Just write me at jobs@jqapi.com :)