How to use jQuery Click Event .click() and stop Event Bubbling

How to use jQuery Click Event .click() and stop Event Bubbling

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 on clicking shows the alert box.

<button id="button1">Click</button>

$("#button1").click(function () {
    alert("I am clicked");
});

Note: Finding any children of an HTML element in the web page can be easily done by the jQuery Children method.

Example 2: Clicking an element without using mouse

Let us suppose ther 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’s click event will also call it’s parent’s 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 executes.

That means I will get 2 alert box shown one by one. First one will show – ‘Child is clicked’ while the next one will show – ‘Parent is clicked’.

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!

Check the below links to:

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 "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.