views:

2557

answers:

4

I have this right now:

$(document).click(function(e) { alert('clicked'); });

In Firefox, this event is firing when I left-click OR right-click. I only want it to fire when I left-click.

Does attaching a click handler to the document work differently than attaching it to other elements? For other elements, it only seems to fire on left clicks.

Is there a way to detect only left clicks besides looking at e.button, which is browser-dependent?

Thanks

+1  A: 

EDIT: missed the bit where you asked not to use e.button... sorry!

however, the example here returns the same ID regardless of looking at it in FF or IE, and uses e.button. could possibly have updated the jQuery framework? of course the other answer is that older versions of IE return a different value, which would be a pain. unfortuantely I only have IE 7/8 here to test against.

PRE EDIT answer:

try

$(document).click(function(e) { 
if (e.button == 0) {
// was the left button
alert('clicked'); 
}
});

however, there seems to be some confusion as to whether IE returns 1 or 0 as left click, you may need to test this :)

further reading here: jQuery Gotcha

Zeus
It looks like the click handler functions differently depending on the element it's attached to. For the document element, it handles both left and right clicks, so there doesn't seem to be any way around checking e.button.
Emmett
A: 

I've read that if you bind with "live" in jQuery 1.3, jQuery normalizes the click between browsers. I've not tested this.

However, this would indicate that it doesn't: http://abeautifulsite.net/notebook/99

Since you say click works correctly everywhere but on "document," have you tried a 100% div over the document to catch the click?

Nosredna
A: 

There is no not-browser-dependent way to detect only left-clicks. You can use this code that works under IE and non-IE browsers:

$("#element").live('click', function(e) {

    if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {

        // Left mouse button was clicked (all browsers)

    }

});

Taken from: http://abeautifulsite.net/notebook/99

fmartin
+1  A: 

You could simply register for a "contextmenu" event like this:

$(document).bind("contextmenu",function(e){
    return false;
});

Taken from: http://www.catswhocode.com/blog/8-awesome-jquery-tips-and-tricks

Krishna Sharma