Why we use stopPropagation and preventDefault in jQuery
Posted By : Avilash Choudhary | 16-Jun-2016
When we define the click events for different ids and classes, most of the time we just use the stopPropagation and preventDefault and then our code works fine. But we don’t know the actual reason behind this why we write these two statements and what are these for.
<div id="challengeTakePhoto">
<span id="cancel-btn">
</span>
</div>
$('#cancel-btn').on('tap', function(e) {
alert(“cancel event...");
});
$('#challengeTakePhoto').on('tap', function(e) {
alert(“take photo event...");
});
In the above code, there are some html elements and some events are defined. Now when we click on cancel-btn the child event, then both the clicks will be fired the cancel-btn and challegeTakePhoto, this type of chaining of events is called bubbling. if we click on challengeTakePhoto then only this event will be fired because its a parent element. To stop the chaining of events we use stopPropagation which won’t allow the bubbling of events.
$('#cancel-btn').on('tap', function(e) {
e.stopPropagation();
alert(“cancel event...");
});
preventDefault is used to preclude the default behaviour or default action of browser. you can also use the return false to achieve the same.
$('#cancel-btn').on('tap', function(e) {
e.stopPropagation();
e.preventDefault();
alert(“cancel event...");
});
THANKS
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Avilash Choudhary
Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.