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?
Share
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/
The state of the mouse is tracked in a variable and set in the button’s handlers for
mousedownandmouseup. Themouseupis also tracked at thedocumentlevel. This will help themouseenterpart of the.hover()to know if it should set thepressedclass 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, themouseupwould not be detected by thedocument.)EDIT: Made it so the
documentonly tracksmouseup, and the button tracks both.