Reputation: 43
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");
});
Upvotes: 4
Views: 6544
Reputation: 5690
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.
Upvotes: 0
Reputation: 121
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.
$(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");
});
Upvotes: 6
Reputation: 9224
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.
Upvotes: 0
Reputation: 223
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.
$(document).mousedown(function(){
console.log('test');
});
$(document).mouseup(function(){
console.log('test2');
});
Upvotes: 0
Reputation: 1
try putting your code into the ready-function like this:
$(document).ready(function(){
$(document).mousedown(function(e){
e.preventDefault();
alert("down");
});
});
Upvotes: -1