7

See this jsfiddle:

http://jsfiddle.net/CB87X/6/

Click and hold the button, drag off the button and release. As you can see, the mouseup event never fires if the mouse is not over the element when the mouse button is released. Thus, the styling in my example never changes back to its original. How do you fire the mouseup event if the mouse button is released when not over the clicked element?

Edit1: BTW I have looked at several solutions on this site, implemented them, and the mouseup event still did not fire.

preahkumpii
  • 1,301
  • 4
  • 21
  • 36

4 Answers4

10

The mouseup event is relative to where the pointer is and this is expected behaviour. If you want your button to style properly, bind the mouseleave event as well.

Alasjo
  • 1,240
  • 8
  • 17
  • By "as well" I assume that you can bind two events to one selector? If so, can you show me how? Do I just add a separate function? – preahkumpii Sep 10 '12 at 09:31
  • 6
    Add events seperated by `space`. `$(".but").bind("mouseup mouseleave",function() { ... }` – alexbusu Sep 10 '12 at 09:51
  • +1 for for providing the can opener to this can of worms *(of having to manage the mouseleaves and mouse re-entry if merely dropping the effect while the button is held is not enough)* Thanks, though. :-) – HostileFork says dont trust SE Mar 15 '14 at 15:18
4

This should do the trick. If you left click on the button (.but) and drag off, you can mouseup anywhere on the page and still fire the click event. If you mouseleave the page 'body' and mouseup, the binded mouseleave event is unbinded.

$('.but').mousedown( function(e) {
    if (e.which == 1) {
        var $this = $(this);
        $this.bind('mouseleave', function(){
            $('body').one('mouseup', function() {
                $this.click();
            });
        });
        $this.mouseup(function() {
            $(this).unbind('mouseleave');
        });
    }
});
Robert Waddell
  • 879
  • 7
  • 15
2

Forked your exemple to provide a working example:

http://jsfiddle.net/67Rrs/2/

Once the button is mousedowned, an event is bound to the next mouseup, wherever it happens, that resets the style.

Barney
  • 16,181
  • 5
  • 62
  • 76
0

Just use $(document).on('mouseup dragend', somefunc);

Martin Zvarík
  • 2,120
  • 22
  • 27