Re-write jQuery script to animate an element based on mouse movement.
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I have a side navigation element that fades in during mouse movement, and then fades out after a setTimeout when the mouse stops. I'd like to amend this so that the element is hidden outside the window by default and then slides into view on mouse movement (no fading at all). Then to animate back out after a setTimeout when the mouse stops.

I tried this already with .animate() but the setTimeout() didn't seem to work. I'd like to see other people's ways of doing this. It must be stable e.g. no queuing, lagginess, and compatible on FF, Chrome, IE 7+, Safari, Opera.

    html, body {
        font-family: Arial, Verdana, Tahoma;
    #nav {
        width: 50px;
        position: fixed;
        top: 0px;
        left: 0px;
     /* left: -50px */
        background: #333;
        padding:10px 0 10px 0;

    a {
        padding: 10px;
        text-decoration: none;
        color: #fff;
        font-size: 40px;

        $(document).ready(function() {
        var timer, p = $("#nav");
        $(document).on("mousemove", "body", function() {     
           // p.animate({left:"0px"},300);
                timer = setTimeout(function(){
                   // p.animate({left:"-50px"},300);
                }, 1000);

<div id="nav">
    <a href="#">1</a>
    <a href="#">2</a>
    <a href="#">3</a>
    <a href="#">4</a>
awarded to Wikimedia via slang

Crowdsource coding tasks.

4 Solutions

The mousestop library might help.

Here's your code rewritten to use mousestop. Beware has problems with IE.

in Firefox, on linux (and maybe other browsers), the nav element doesn't re-hide.
slang almost 10 years ago

Just doing some changes to your codes I made it work fine. You can not call animate every mouse move.

I created an example here:

You should just check left of the element, and limit the animation queue than it will work as you expected.

here is a jsFiddle example.


Another solution is clearQueue()

If you clear animation queue and stop the last animation before hiding it, that will work as you expected again.

Winning solution

I edited your code and this works: . However, it is really laggy because every single mouse movement triggers your function, so because the script needs to catch up, the delay ends up being more than 1000ms.

I will continue to edit the gist to make the code more efficant...

EDIT: I switched to using setInterval() to improve performance, now I just need to add the 1000ms delay before hiding.

EDIT: It's working perfectly! :) You can see it working here. I also made it hide when the mouse is moved outside of the browser window, using jQuery's mouseout().

View Timeline