user1912899
user1912899

Reputation:

jQuery mousemove: have navbar appear only when mouse moves

I've figured out how to have a navbar appear on mousemove, but I'm have trouble figuring out how to have it disappear again after the mouse stops moving.

CSS

nav{
  display:none;
}

JavaScript

$(document).mousemove(function(event) {     
  $("nav").css("display", "block");
});

I'm sure there's an easy solution, but I've been looking for a while to no avail.

Thanks!

Upvotes: 1

Views: 2389

Answers (3)

jasonmerino
jasonmerino

Reputation: 3240

You could just use a timeout system like this:

var timer;

$(window).on('mousemove', function () {
  $('nav').addClass('show');
  try {
    clearTimeout(timer);
  } catch (e) {}
  timer = setTimeout(function () {
    $('nav').removeClass('show');
  }, 50);
});

With styles like this:

nav {
  background: #333;
  color: #fff;
  visibility: hidden;
  opacity: 0;
  transition: all .5s ease;
}

nav.show {
  opacity: 1;
  visibility: visible;
}

The 50ms makes it adjustable to how sensitive you want it to be.

Upvotes: 4

Simon
Simon

Reputation: 168

There is no native event in jQuery for the end of mousemove, but you can use some of the various jQuery plugins for mousestop on the internet like

http://www.jquery4u.com/events/writing-mousestop-event-plugin-jquery/

Then, you can do something like this:

$(document).mousemove(function(event){     
    $("nav").show();
});

$(document).mousestop(function(e) {
    $("nav").hide();
});

Upvotes: 0

DSlagle
DSlagle

Reputation: 1583

You could register a mouse stop event on mouse move and remove the event after it has been called. Since you are using jQuery you can also use .show() and .hide() instead of changing the css directly. You can get a plugin for a mouse stop event here

$(document).mousemove(function(event){     
    $("nav").show();
    $(document).mousestop(function(e) {
        $("nav").hide();
        $(document).unbind('mousestop');
    });
});

If you decide to you .show and .hide you should take a look at the api documentation. With a few extra params you can easily show and hide with a nice animation instead of an instant appear and disappear

jQuery show

jQuery hide

Upvotes: 2

Related Questions