Description: Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
handler(eventObject)A function to execute each time the event is triggered.
This method is a shortcut for .bind('click', handler)
in the first variation, and .trigger('click')
in the second.
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>
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, clicks on Trigger the handler will also alert the message.
The click
event is only triggered after this exact series of events:
This is usually the desired sequence before taking an action. If this is not required, the mousedown
or mouseup
event may be more suitable.
<!DOCTYPE html>
<html>
<head>
<style>
p { color:red; margin:5px; cursor:pointer; }
p.hilite { background:yellow; }
</style>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>
$("p").click(function () {
$(this).slideUp();
});
$("p").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
</script>
</body>
</html>
$("p").click();