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.

Related blogs
- 01jquery-ujs and jquery triggerMay 11, 2012 · Neeraj Singh
- 02An inline confirmation utility powered by jQueryNovember 2, 2010 · Neeraj Singh
- 03Return false has changed in jquery 1.4.3October 25, 2010 · Neeraj Singh
- 04List of only the elements that containsApril 12, 2010 · Neeraj Singh