Event Delegation

Imagine that you have 100 paragraphs on a page and you want something to happen every time a user clicks one of them. Knowing what you do about jQuery, you would probably, quite reasonably, write something like this:

$("p").on("click", function() {
//do something here
});

And this would work fine, but it is terribly inefficient. Why? Because it will iterate through all the <p> tags, but what if we don’t want it on some of the <p> tags and want it on some of <p> tags. For solving this problem we use event delegation in jQuery.
 
The following code will display 7 paragraphs but alert event work on first 5 paragraphs and on 6 and 7th it doesn’t.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
</head>
<body>
	<p>Paragraph 1</p>
	<p>Paragraph 2</p>
	<p>Paragraph 3</p>
	<p>Paragraph 4</p>
	<p>Paragraph 5</p>
	<script>	
	$("p").click(function() {
		alert("p clicked");
	});

	// Dynamically add paragraph 6, event will not work for this paragraph 

	$("<p />", {
		text: "Paragraph 6"
		}).appendTo("body");

	// Dynamically add paragraph 7, event will not work for this paragraph

	$("<p />", {
		text: "Paragraph 7"
		}).appendTo("body");

</script>
</body>
</html>