views:

229

answers:

3

I have some code that runs when a user clicks anywhere in the body of the web page. I only want the JavaScript to run if the click is on a NON-LINK. Any ideas?

Thanks
Mike

+9  A: 
document.body.onclick = function(e){
    var target = e ? e.target : window.event.srcElement;
    if (target.nodeName.toLowerCase() !== 'a') {
        // Do something here...
    }
};

Note that any attempts to stop propagation before the event reaches the <body> will stop the above handler from running. To avoid this you can use event capturing.

J-P
Do I call this like so: <body onclick="function(e)">? Why is there a semicolon after the last brace? Thanks!
Mike
There's a semi-colon because it's a variable deceleration; and, no, you don't need to add the event obtrusively; the code above works - just put it in a SCRIPT tag somewhere within the BODY :)
J-P
This will be called on any onclick events regarding the body of the site (every event), e is passed as the element. The semicolon is there because this is assigning a block.
ONi
This will incorrectly fail on anchors, e.g. <a name="foo">Stuff about Foo</a>.
NickFitz
A: 

document.body.onclick = function... is a statement. Hence the closing ';'

Everyone
A: 

Use jQuery.

$(function() {
   $("body").click( function() { /* your code here */ } );
   $("a").click( function(e) { e.stopPropagation(); } );
});

jQuery home.

lox
Note: Script goes into your HTML head, you also need a reference to the jQuery library and "$(function()" is short for "$(document).ready( function()". You can find all the information you need at the jQuery site.
lox