views:

27

answers:

2

Hi,

I have a CSS button that has normal, pressed and hover states. Everything works fine except that when the click has happened, I need to somehow know whether the style should be set to normal or hover. That is, I need a way of knowing if the mouse cursor is still hovering the element. How would one achieve this with JavaScript?

+1  A: 

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.

patrick dw
A: 

You don't have a :visited state in your CSS? As for Javascript, OnMouseOver or JQuery mouseover, hover or mouseenter (depending on what you want to do) will tell you when the hover is happening.

Dave Everitt