Black friday

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

Control the onclick Event with jQuery .click()

Reading time 2 min
Published Dec 29, 2017
Updated Oct 9, 2019

jQuery click: Main Tips

  • The jQuery .click() method is a shortcut of using .trigger() or .on() with click as the first parameter.
  • Without any parameters specified, jQuery .click() triggers an onclick event.
  • If you define one or two parameters, it can attach an event handler to run when the jQuery onclick event occurs.
Theory is great, but we recommend digging deeper!

.click() Explained

In its simplest form, the jQuery .click() method can trigger an onclick event. However, if you specify at least one parameter, it can attach an event handler which is triggered when the selected element is clicked.

When users click on a paragraph in the example below, the jQuery onclick event is invoked, and an alert shows:

Example
$(document).ready(() => {
  $("p").click(() => {
    alert("The paragraph was clicked!");
  });
});

Syntax Rules for .click() in jQuery

The jQuery .click() example below demonstrates the syntax required for triggering the event. It is very easy to memorize - you don't need to specify any arguments:

$(selector).click()

To attach an event handler with the jQuery .click(), the syntax is a bit more complicated:

$(selector).click(data, callback)

You can see there are two arguments you can define:

  • The data is an object that contains data passed to the event handler defined in the next parameter. It is optional to include, as not all functions require additional information to run.
  • The callback represents the event handler, also called the callback function. jQuery .click() will execute this function every time the event is triggered. You must include this argument if you want to attach a function: if you skip it, all jQuery .click() will do is trigger the onclick event.