.click()

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

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

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.

  • As the .click() method is just a shorthand for .on( "click", handler ), detaching is possible using .off( "click" ).
version added: 1.0
handler
Function( Event eventObject )

A function to execute each time the event is triggered.

version added: 1.4.3
eventData

An object containing data that will be passed to the event handler.

handler
Function( Event eventObject )

A function to execute each time the event is triggered.

version added: 1.0
This signature does not accept any arguments.
Examples:

Hide paragraphs on a page when they are clicked:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>click demo</title>
  <style>
  p {
    color: red;
    margin: 5px;
    cursor: pointer;
  }
  p:hover {
    background: yellow;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
 
<script>
$( "p" ).click(function() {
  $( this ).slideUp();
});
</script>
 
</body>
</html>

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

$( "p" ).click();
doc_jQuery
2016-03-27 13:48:05
Comments
Leave a Comment

Please login to continue.