jQuery click: Main Tips
- The jQuery
.click()
method is a shortcut of using .trigger() or .on() withclick
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.
- 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
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- 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:
$(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.