I want to make divs on my site 'depress' when clicked by adding a slight margin to the top. I thought .mousedown/up would be good for this except for the case where the user moves the mouse off the div mid-click. In this case, the dive stays depressed and will move down even further from its original position every time it happens
$(document).ready(function() {
$('#foo').mousedown(function() {
$('#foo').css('margin-top', '+=2px')
})
$('#foo').mouseup(function() {
$('#foo').css('margin-top', '-=2px')
})
})
How do I stop this from happening? Is it better to use a different method than .mousedown?
I altered your code so that the mousedown
event stores the depressed button in a variable and altered the mouseup
event to work on the entire document. It will check to see if there is a depressed button and if so it will undepress the button.
$(document).ready(function() {
var depressedButton = null;
$('#foo').mousedown(function() {
depressedButton = $(this);
depressedButton.css('margin-top', '+=2px')
})
$(document).mouseup(function() {
if(depressedButton) depressedButton.css('margin-top', '-=2px')
depressedButton = null;
})
})