If you're concerned about the user doing a mousedown
, then moving the pointer off (and perhaps on again) the button, you could do something like this:
EXAMPLE: http://jsfiddle.net/7zUaj/1/
var mouseIsDown = false; // Track/remember mouse up/down state for the button
// Handle mouseenter and mouseleave
$('div').hover(function() {
$(this).addClass('hover');
if (mouseIsDown)
$(this).addClass('pressed'); // If mouse button was down, and user exited
// and reentered the button, add "pressed"
}, function() {
$(this).removeClass('hover pressed'); // Remove both hover and pressed when
// the pointer leaves the button
})
// Handle the mousedown, track that it is down, and add "pressed" class
.mousedown(function() {
mouseIsDown = true;
$(this).addClass('pressed');
})
// Handle the mouseup, track that it is now up, and remove the "pressed" class
.mouseup(function() {
mouseIsDown = false;
$(this).removeClass('pressed');
});
// If user does mousedown, leaves the button, and does mouseup,
// track that it is now up
$(document).mouseup(function() {
mouseIsDown = false;
});
The state of the mouse is tracked in a variable and set in the button's handlers for mousedown
and mouseup
. The mouseup
is also tracked at the document
level. This will help the mouseenter
part of the .hover()
to know if it should set the pressed
class or not.
(Note that because the mouseup is also tracked on the document
, if there are any other elements on the page that stop the event from bubbling, the mouseup
would not be detected by the document
.)
EDIT: Made it so the document
only tracks mouseup
, and the button tracks both.