How to use jQuery Click Event .click()

How to use jQuery Click Event .click()

The jQuery Click event – .click() is fired whenever an element is clicked.

Syntax of jQuery Click Event

$(selector) .click(function () {
    // code
]);

Example 1: Clicking a button

The below code has a button which when clicked shows the alert box.

<button id="button1">Click</button>
$("#button1").click(function () {
    alert("I am clicked");
});

Example 2: Clicking an element without using mouse

Let us suppose you have 2 buttonsbutton 1 and button 2. I want to execute the button 1 click event on the button 2 click.

This is how to do it:

<button id="button1">Click</button>
<button id="button2">Click</button>
$("#button2").click(function () {
    $("#button1").click();
});

$("#button1").click(function () {
    alert("Button 1 clicked");
});

I have just called $(“#button1”).click(); inside the button 2 click event and that will call the click event of button 1.

Using event.stopPropagation() in jQuery Click

The click event will bubble up the DOM tree. This means any child click event will also call its parent click event.

Suppose I have a div with a child element p. They both have their click events.

<div id="parent">
    Parent
    <p id="child">Child</p>
</div>

$("#parent").click(function () {
    alert("Parent is clicked");
});

$("#child").click(function () {
    alert("Child is clicked");
});

When I click the child element p, first the click event of the child executes then the click event of parent is executed. This is definitely not what I wanted.

Fortunately jQuery has .stopPropagation() method to stop it.

Update the child code to include .stopPropagation() method call.

$("#child").click(function (e) {
    e.stopPropagation();
    alert("Child is clicked");
});

jQuery Click Event Bubbling Problem Solved!

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.