Event propagation and peventDefault

Neeraj Singh

Neeraj Singh

July 20, 2009

Let's look at sample html.

<div id="parent">
  Languages
  <p>Java</p>
  <p>Javascript</p>
</div>

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

$(document).ready(function () {
  $("#parent").click(function () {
    alert("parent was clicked");
  });
  $("#parent p").click(function () {
    alert("p was clicked");
  });
});

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.

$(document).ready(function () {
  $("#parent").click(function () {
    alert("parent was clicked");
  });
  $("#parent p").click(function (e) {
    alert("p was clicked");
    e.stopPropagation();
  });
});

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.

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

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

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

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.