简体   繁体   中英

Mouseup not firing after mousedown in jQuery

When I click, I get an alert saying "down" but not "up." I read that e.preventDefault() should fix the problem, but it hasn't. Does anyone have any suggestions?

$(document).mousedown(function(e){
    e.preventDefault();
    alert("down");
});
$(document).mouseup(function(e){
    alert("up");
});

The problem is that the mousedown alert is up and blocking the mouseup from being fired. If you do the mouse up only it works fine, or if you use anything other than an alert window this method will work.

JSFiddle for the mouseup only

$(document).mouseup(function(e){
    alert("up");
});

A second example with an input box: http://jsfiddle.net/YRqe8/2/

$(document).mousedown(function(e){
    $("#text").val("mousedown");
});   
$(document).mouseup(function(e){
    $("#text").val("mouseup");
});

It's because the alert being shown from the mousedown event is blocking the mouseup event from firing.

If you use console.log instead, you'll see both events are firing as expected.

http://jsfiddle.net/Ca9q3/

$(document).mousedown(function(){
    console.log('test');
});
$(document).mouseup(function(){
    console.log('test2');
});

The problem is that when the down alert happens, the document loses focus and the alert box gets the focus. So when you let go of the button, it isn't captured by the document, because it's happening to the alert box.

I think you'll find that if you switch your alert() 's to console.log() 's, it'll work.

It doesn't prevent the mouseup even from being fired. It actually works as you would expect with a minor caveat thrown into the mix with the alert in your example.

The alert dialog box is out of scope of the window, when you mouse up with the dialog active in focus the event goes to the alert. If you click and hold your mouse button and close the alert with the enter key, you will find that the mouseup event will fire when you release the button.

try putting your code into the ready-function like this:

$(document).ready(function(){
  $(document).mousedown(function(e){
    e.preventDefault();
    alert("down");
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM