Event propagation and peventDefault

Neeraj Singh

Neeraj Singh

July 20, 2009

Let's look at sample html.

1<div id="parent">
2  Languages
3  <p>Java</p>
4  <p>Javascript</p>
5</div>

And here is the javascript code. Run the code with jQuery-1.3.2 .

1$(document).ready(function () {
2  $("#parent").click(function () {
3    alert("parent was clicked");
4  });
5  $("#parent p").click(function () {
6    alert("p was clicked");
7  });
8});

When you click on Java then you will get two alerts. That is because the click on element p will propagate outward and it will be caught by element div which has onclick trigger.

If you do not want the event to propagate then here is a way to stop it.

1$(document).ready(function () {
2  $("#parent").click(function () {
3    alert("parent was clicked");
4  });
5  $("#parent p").click(function (e) {
6    alert("p was clicked");
7    e.stopPropagation();
8  });
9});

Stopping the default behavior

Converting a regular html link into an AJAX request is easy. One of the things you need to do is to return false so that the click operation does not perform its default behavior.

1$("a").bind("click", function () {
2  alert("clicked");
3  return false;
4});

However there is another way to handle such cases. preventDefault stops the default behavior. The same code could be written as

1$("a").bind("click", function (e) {
2  e.preventDefault();
3  alert("clicked");
4});

Not sure why but I have noticed that e.preventDefault() should be the first line in the function. If I switch the order of e.preventDefault and alert message in the above javascript then it does not work in Firefox/mac.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.