Michael Swarts
Michael Swarts

Reputation: 3921

How can I execute JavaScript onClick of a NON-LINK?

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

Upvotes: 1

Views: 365

Answers (3)

lox
lox

Reputation: 1622

Use jQuery.

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

jQuery home.

Upvotes: 0

Everyone
Everyone

Reputation: 2376

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

Upvotes: 0

James
James

Reputation: 111950

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.

Upvotes: 9

Related Questions