Detect mouse hover on page load with jQuery

前端 未结 5 1598
渐次进展
渐次进展 2021-01-19 04:01

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

5条回答
  •  温柔的废话
    2021-01-19 04:02

    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)
                }
            });
        }
    }
    

提交回复
热议问题