jQuery.live("click") Gotcha

If you're using the new jQuery.live("type", fn) handlers in jQuery 1.3, be careful with the "click" event type.  Unlike jQuery.bind("click", fn) and jQuery.click(fn), jQuery.live("click", fn) doesn't distinguish between mouse buttons.  So while the "normal" handlers will only trigger when the left button is used, the live handler will trigger on any button.

The workaround is pretty simple, though kind of kludgey: add the stuff in bold to your handler.

jQuery("#selector").live("click", function(event) {
  if (event.button != 0) {
    // wasn't the left button - ignore
    return true;
  }
  // do some stuff
  return false; // "capture" the click
});

Hopefully this will be addressed in the future, but for right now you have to pick between manual button detection and sticking with the "normal" handlers.

12 responses to “jQuery.live("click") Gotcha”

  1. Hal Helms

    nice find, Barney. Thanks

  2. nirvana

    NOTE: Internet Explorer treats left-click events as button 1. FF/Safari, etc all treat it as button 0.

  3. Jason

    The 'button' event attribute is not normalized by jQuery. But it does normalize event.which to be 1,2,3 depending on the button clicked (1=left,2=middle,3=right).

    So use event.which instead of event.button.

  4. Daniel Tsadok

    event.which is returning undefined in IE7…

  5. jeffery

    same behaviour with the third mouse button.

  6. Resourcednet

    Is this script possible to detect Adsense click?

  7. Resourcednet
  8. Candace Camarillo

    I love searching for bug reports and finding you :-)

  9. Mike Cotton

    I learned something on a project I was working on the other day. I was having trouble figuring out whether to use the which event or the button event when trying to detect what button was clicked in different browsers. Using the button event values returned inconsistent results. Using the which event value was more consistent but IE always returned it as undefined/null. Here is what I did to make it work for me.

    $(#target").live("mouseup", function(event){
         if(event.which == null){
              // this is ie, left button is 1, right button is 2, middle button is 4
              if(event.button == 1){
                   // left button clicked
                   doSomething();
              }
         }else{
              //all other browsers, left which is 1, right which is 3, middle which is 2
              if(event.which == 1){
                   // left button clicked
                   doSomething();
              }
         }
    });