jQuery $.live(‘click’) Binds Both the Left and Right Mouse Buttons

Update: This issue has been fixed as of jQuery 1.4.1. I would recommend upgrading if possible.  That said, the solution below still applies to jQuery 1.4 and below.

Here’s a little gotcha that I uncovered while working with jQuery’s $.live() handler. In short, $.live(‘click’) will detect both left and right mouse clicks (and probably middle clicks, as well). In other words, if you’re expecting to only fire an event on a left click, you’ll have to test for it and, unfortunately, Internet Explorer likes to behave differently here.

So, for all non-IE browsers you can do this:

$("#element").live('click', function(e) {
    if( e.button == 0 ) {
        // Left mouse button was clicked (non-IE)
    }
});

But for IE, you need to do this:

$("#element").live('click', function(e) {
    if( e.button == 1 ) {
        // Left mouse button was clicked (IE only)
    }
});

So let’s make it easier on everyone. Although I hate browser checks, I don’t really know of a way around this without one. (I also realize that $.browser has been deprecated — although still included — in jQuery 1.3.)

$("#element").live('click', function(e) {
    if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
        // Left mouse button was clicked (all browsers)
    }
});

Make sure you include the e argument in your anonymous function, otherwise e will be undefined.

If you enjoyed this article, please share it with a friend!

5 Responses to jQuery $.live(‘click’) Binds Both the Left and Right Mouse Buttons

  1. cjw says:

    I used the following to ignore right-clicks, shift-clicks, ctrl-clicks, etc.

    if(evt.button != ($.browser.msie ? 1 : 0) || evt.ctrlKey || evt.shiftKey || evt.altKey) return;

  2. hsnkvk says:

    Thanks for your share. That helped me too much.

  3. Eric B. says:

    I came across this article while looking at your jQuery ContextMenu Plugin and I can say I was surprise of this behavior and I didn’t know until I see this. Thank you!

  4. Neil Craig says:

    In IE8 the click event is not fired for right-clicks, the left mouse button also returns “0″, and the middle mouse button also returns “0″.

  5. megas says:

    Use which property of the event object. It has normalized values for all the browsers from left to right – 1 to 3.