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.
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
Coursera
Pros
  • Professional service
  • Flexible timetables
  • A variety of features to choose from
Main Features
  • Professional certificates of completion
  • University-level courses
  • Multiple Online degree programs
Datacamp
Pros
  • Great user experience
  • Offers quality content
  • Very transparent with their pricing
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

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

Latest Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 30/01/2021
3176 People Used
Only 97 Left
Rating
5.0