I wanted to detect whether the mouse was over an element when the web page was loaded. It appears this is not possible with jQuery - mouseover, hover etc. require a mouse mo
Here is how I solved it:
/** detect if the mouse was hovering over and element when the page loaded */
function detectHoverOnLoad(options) {
var sel = options.selector
if ($(sel + ':hover').length) {
console.log('loaded while HOVERING over ' + sel)
} else {
console.log('loaded, but NOT hovering over ' + sel)
}
}
then I called it like so:
detectHoverOnLoad({selector: '#headerNav'})
With more testing, I noticed that at times, if the mouse was moving, it did not always detect the hover, so I added a fallback in the else to detect the mouse moving over the element:
function detectHoverOnLoad(options) {
var sel = options.selector
if ($(sel + ':hover').length) {
console.log('loaded while HOVERING over ' + sel)
} else {
console.log('NOT hovering')
$(sel).one('mousemove', function (e) {
if ($(e.target).parents(sel).length) {
console.log('MOUSEMOVEed over ' + sel)
}
});
}
}