views:

53

answers:

4

Sample code:

<div id="a">
     <div id="b">
          Click here
     </div>
</div>

<script>
    $('*').click(function() {
        alert($(this).attr('id'));                    
    });
</script>

When you click 'Click Here' it alerts twice, once with 'b' and then with 'a'.

I need to figure out how to get jQuery to ignore all the parents of where the user clicked and just alert, in this case, 'b'.

+11  A: 

Try this:

  $('*').click(function(e) {
        e.stopPropagation();
        // do something
    });

Here you can find documentation: http://api.jquery.com/event.stopPropagation/

Haim Evgi
Place your alert right after this line:`e.stopPropagation();`
Anriëtte Combrink
+1  A: 

You are using the "All Selector" http://api.jquery.com/all-selector/

I think you are looking for this:

$('#b').click(function() {
    alert( $(this).attr('id') );
});
Fred Bergman
No, I want everything on the page to be clickable, much like when you are using Firebug and you use the 'Click an element to view source' feature.
David B.
This would also work, assuming your element's `id` will always be **b**.
Anriëtte Combrink
+1  A: 

Use stopPropagation:

$('*').click(function(event) {
    alert($(this).attr('id'));
    event.stopPropagation();
});
joshperry
Works great for .click() -- doesn't seem to work for .hover() -- is there a way to do that for hover as well?
David B.
+1  A: 

Try using $('body').delegate('*', 'click', fn) instead of direct event handlers. (See jQuery.delegate.) It will be called exactly once for each event, and you can find out from the event object which element was affected.

Tgr
Perfect thanks!
David B.