Reputation: 12187
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?
Upvotes: 0
Views: 153
Reputation: 1926
You can have a variable checking if you have clicked on the div
. Then, if you didn't trigger mouseup
, but you leave the div
(mouseleave
event), you do the same action as mouseup
.
$(document).ready(function() {
var clicked = false;
$('#foo').mousedown(function() {
clicked = true;
$('#foo').css('margin-top', '+=2px');
})
$('#foo').mouseleave(function() {
if(clicked)
$('#foo').css('margin-top', '-=2px');
clicked = false;
})
$('#foo').mouseup(function() {
if(clicked)
$('#foo').css('margin-top', '-=2px');
clicked = false;
})
})
Fiddle: http://jsfiddle.net/dLwovpd9/2/
Upvotes: 1
Reputation: 35117
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;
})
})
Upvotes: 1