Lets say we have a HTML structure like this
<div id="container">
<div id="nested">
<span id="someElement"></span>
</div>
</div>
...and our goal is to have an event listener on the #container
only ! So, we bind a listener (jQuery code)
$("#container").on('click', function(event) {
alert("container was clicked");
});
That works of course, but my problem with this approach is that, since events usually bubble up, that listener will also fire if we actually click on #nested
or #someElement
. My current solution to only handle the click when the #container
is clicked is to compare this
with event.target
$("#container").on('click', function(event) {
if(this === event.target) {
alert("container was clicked");
}
});
My question: Is that considered "best practice" ? Is there a better way with jQuery to accomplish the same result "out of the box" ?
Example in action: http://jsfiddle.net/FKX7p/