Ric
Ric

Reputation: 3458

Show / hide elements on mouse move

I'm building a site where I want the certain sections to be hidden until the mouse is moved. They then remain visible whilst the mouse is moving, however, if it remains still for a couple of seconds they hide again.

I'm using jQuery on the site, in my ready state I have:

var hide = setTimeout(function() {
    hideNav();
}, 2000);

$('body').mousemove(function() {
    clearTimeout(hide);
    var hide = setTimeout(function() {
        hideNav();
    }, 2000);
    showNav();
});

And the functions that show/hide content

function hideNav() {
  $('#primary').fadeOut(1000);
  var lightbox = $('#lightbox');
  if (lightbox.length) {
    lightbox.fadeOut(1000);
  }
}

function showNav() {
  $('#primary').fadeIn(1000);
  var lightbox = $('#lightbox');
  if (lightbox.length) {
    lightbox.fadeIn(1000);
  }
}

This sort of works, except the timeout for hiding the elements ends up fighting with the function to show it when the mouse moves resulting in a lot of flickering.

EDIT: The mouse movement needs to be for anywhere on the page, not just when hovering over the element that is to be shown/hidden.

Any help would be appreciated.

Thanks

Upvotes: 0

Views: 2834

Answers (1)

Benno
Benno

Reputation: 3008

Try using $.stop http://api.jquery.com/stop/

If its in the 1 second of fading out when you move your mouse, it should stop the animation of fading out and fade back in.

function hideNav() {
$('#primary').stop().fadeOut(1000);
var lightbox = $('#lightbox');
if (lightbox.length) {
    lightbox.fadeOut(1000);
}
}

function showNav() {
$('#primary').stop().fadeIn(1000);
var lightbox = $('#lightbox');
if (lightbox.length) {
    lightbox.fadeIn(1000);
}
}

Also, I would remove var from the var hide = ... in your mousemove function. If hide is a global variable, just reuse it inside mousemove (doesn't need to be redeclared).

Upvotes: 2

Related Questions