Damian Damian - 2 months ago 18
jQuery Question

jQuery mouseover on page load

I have created a drop down menu using jQuery's mouseover event.
I would like to stop the event triggering if the cursor is over the menu on page load.

What I have seen happening is, the user clicks on a menu item which causes the relevant page to load. If they don't move their cursor, when the next page has loaded the mouseover event automatically fires becuase they are still hovering over the menu!

When this happens, the user doesn't realise the page has loaded; they just sit there waiting.

If you'd like to see what I mean, go to www.snowrepublic.co.uk and click on say, Gloves but dont move your cursor.
The Gloves page will load then the menu will instantly drop down. It's quite a large menu so you can see where the confusion comes from!

Here's my code:

<script type="text/javascript">
$(document).ready(function() {
// Dropdown delay
var $over = false;
$('#header-nav li .nav').removeClass('drop');
$('#header-nav li').mouseover(function(){
$over = true;
setTimeout( function(){ if ($over == true) $('#header-nav li .nav').addClass('drop'); }, 200 );

$('#header-nav li').mouseout(function(){
$over = false;
setTimeout( function(){ if ($over == false) $('#header-nav li .nav').removeClass('drop'); }, 200 );

Any way to stop the mouseover event firing on page load?

This is strange...I've just noticed this seems to be an intermittent problem. Sometimes the menu doesn't drop down on page load, other times it does????


Not sure why you are getting the effect.. but there is one way to make sure it never happens..

Just bound your code on the first mousemove that occurs in the page ..

$(document).ready(function() { 
    $(document).one('mousemove', function() {  
      // YOUR CODE HERE...

This will only fire once, on the first mousemove, and bind the events then.. so nothing can happen before the user moves his mouse ...

Demo at http://jsfiddle.net/gaby/4ALmC/embedded/result/

reference : .one()

The .one() method is identical to .on(), except that the handler is unbound after its first invocation.


Ok, this looks like a IE/FF 5+ bug (or maybe jQuery bug)..

A workaround for now would be to wrap all this in a timeout to avoid the initial mess in those browsers..

$(document).ready(function() { 
        $(document).one('mousemove', function() {  

            // YOUR CODE HERE...

    }, 100);