maxp
maxp

Reputation: 25161

Excluding Elements In Javascript / DOM

Given the html / css / javascript/jquery as follows, the event still fires when I click on '#bbb'.

Is there anyway to avoid this from happening?

<div id="aaa" style="position:absolute; width:100%; height:100%; background-color:#f00;">
   <div id="bbb" style="height:25%; width:25%; background-color:#0f0; margin:0 auto;">
   </div>
</div>

<script type="text/javascript">
   $('#aaa').click(function(){alert('aaa clicked');});
</script>

Upvotes: 1

Views: 99

Answers (3)

Šime Vidas
Šime Vidas

Reputation: 186063

Here you go:

$( '#aaa' ).click(function (e) { 
    if ( e.target !== this ) { return; }
    alert( 'aaa clicked' );
});

e.target points to the DOM element at which the click event was fired. this points to the #aaa element (because it's his click handler). Therefore, this line

if ( e.target !== this ) { return; }

will terminate the click handler early if the #aaa element wasn't clicked directly.

Live demo: http://jsfiddle.net/qbDZy/

Upvotes: 5

Seb T.
Seb T.

Reputation: 1124

From my understanding as bbb element is nested within aaa element, you will probably have to handle click event in bbb element as well.

$('#aaa').click(function(event){event.stopPropagation(); alert('aaa clicked');});
$('#bbb').click(function(event){event.stopPropagation(); alert('bbb clicked');});

But do not forget to consider stoping event propagation or both event listener will get notified.

You can see source code in action here

Hope this helps.

Upvotes: 1

mplungjan
mplungjan

Reputation: 178385

You want to cancel the event bubbling (event propagation)
http://www.quirksmode.org/js/events_order.html

DEMO HERE

$('#aaa').click(function(){alert('aaa clicked');});
$('#bbb').click(function(event){alert('bbb clicked');  event.stopPropagation();});   

Upvotes: 1

Related Questions