The jQuery Click event – .click() is fired 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");
});
Let us suppose ther have 2 buttons – button 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.
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 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