
The jQuery click event, .click(), is triggered whenever an element is clicked.
$(selector) .click(function () {
// code
});
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");
});
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.
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:
1. Understanding the jQuery scrollTop Method with Examples
2. Multiple ways of using jQuery On Method – .on() – in your Website
3. jQuery Val Method – .val() – Complete Usage Guide with Codes