---
title: "Event propagation and peventDefault"
description:
  "DOM propagates events and JavaScript can intercept those events and can act
  on it. Concepts like preventDefault in jQuery could be confusing. This blog
  discusses that."
canonical_url: "https://www.bigbinary.com/blog/event-propagation-and-peventdefault"
markdown_url: "https://www.bigbinary.com/blog/event-propagation-and-peventdefault.md"
---

# Event propagation and peventDefault

DOM propagates events and JavaScript can intercept those events and can act on
it. Concepts like preventDefault in jQuery could be confusing. This blog
discusses that.

- Author: Neeraj Singh
- Published: July 20, 2009
- Categories: jQuery

Let's look at sample html.

```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 .

```javascript
$(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.

```javascript
$(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.

```javascript
$("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

```javascript
$("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_.

## Links

- [Human page](https://www.bigbinary.com/blog/event-propagation-and-peventdefault)
