🔥 $100K Hit! Where Will Bitcoin Go Next? Find Out Live!

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.
DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
edX
Pros
  • A wide range of learning programs
  • University-level courses
  • Easy to navigate
  • Verified certificates
  • Free learning track available
Main Features
  • University-level courses
  • Suitable for enterprises
  • Verified certificates of completion

.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.