preventing default behaviour with Event Propagation

Imagine that I have a div, and within that div, there’s a heading. I want to run one piece of code when the div is clicked, and another when the heading is clicked. For this consider the following code

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(function() {
	$("h5").on("click", function() {
		alert("h5 Click");
		});

	$("div").on("click", function() {
		alert("div Click");
		});
	});
</script>
</head>
<body>
	<div>
		<h5>Click me</h5>
	</div>
</body>
</html>

Refresh your browser and click the div. You’ll see the correct alert, “div Click”. Now click the h5 Click. You will see two alerts pop up—one with the text “h5 Click” and the other with “div Click”. What just happened there? When we click text inside h5 the event of h5 occurred ans for div it is also occurred. So there is some default events that are associated with text also fired.
 
While the event object contains a lot of information about the event, it also contains methods that you can use. One of those methods is stopPropagation. Here’s what the docs have to say about it: “Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.”

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(function() {
	$("h5").on("click", function(event) {
		alert("h5 Click");
		event.stopPropagation();
	});

	$("div").on("click", function() {
		alert("div click");
	});
});
</script>
</head>
<body>
	<div>
		<h5>Click me</h5>
	</div>
</body>
</html>