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

Suppose there are two buttons, button 1 and button 2. I want clicking button 2 to also run the button 1 click event.

Here 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");
});

Inside the button 2 click event, I call $(“#button1”).click();, which triggers the click event of button 1.

Using event.stopPropagation() in jQuery Click

When an element is clicked, the event bubbles up to its parent elements, so any click handlers on the parents run as well. To prevent this, I will use event.stopPropagation() inside the click event. It stops the event from reaching the parent elements, so only the handler of the clicked element runs.

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");
});

Now the jQuery Click Event Bubbling Problem is Solved!

Check the below link:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate