Why we use stopPropagation and preventDefault in jQuery

Posted By : Avilash Choudhary | 16-Jun-2016

Why we use StopPropagation JQuery

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

About Author

Author Image
Avilash Choudhary

Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..