The terms you're looking for here are Event Propagation or Event Bubbling.
The event handling in "modern" browsers (which is the model most libraries hook into) works by bubbling up the document tree. What that means is if you have html document structure like this
<body>
<div>
<ul>
<li>Foo</li>
<li>Bar</li>
<li>Baz</li>
</ul>
</div>
</body>
and someone clicks on Foo, the following event stuff happens
- The <li> receives a click event
- The <ul> receives a click event
- The <div> receives a click event
- The <body> receives a click event
That's what's happening to you. There's two things you can do to prevent this.
The first, as many have suggested is, if your event handler returns false, then event propagation will stop at the element that has been clicked. (this is how jQuery handles it, each library has a different approach)
$(document).ready(function() {
//hookup events for entire body of document
$('body').bind('click', function(e){
//do clicked body stuff
});
//hookup our divs, returning false to prevent bubbling
$('div').bind('click', function(e){
//do clicked div stuff
return false; //stop event propagation
});
});
A second, some would argue better, approach is to use event delegation. Event delegation, in the context of Javascript and the DOM, is where you attach a single event handler to an outer element (in this case the body), and then based on what element was originally clicked, take a particular action.
Something like this.
$(document).ready(function() {
//event delegate
$('body').bind('click', function(e){
var originalElement = e.srcElement;
if(!originalElement){originalElement=e.originalTarget;}
if ($(originalElement).is('div')) {
console.log("A div!");
}
else if ($(originalElement).is('div#inside')) {
console.log("A Specific Div!");
}
else{
console.log("Something else!");
}
});
});
The benifits of this are two-fold. First, you can centralize all your event handling code into a single place in your code. The second (more important in my mind) is attaching a single event handler consumes much less browser memory and sets you up for better performance moving forward.