Xtian
Xtian

Reputation: 3587

Animate Menu on Mouse movement

I have a function that i would like a menu in from the left side of the page when the mouse is moved to the left side of the screen. And the slide off the left side of the page when the mouse is moved away from the left side.

The issue is since the function is always recording my mouse movements, if the mouse if moved it will register it is past the point and constantly toggle the menu. I need it to only toggle the menu when it goes past a certain X-coordinate

JS: (EDITED CODE)

$("#gridcontainer").mousemove(function(e){

 var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
 var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
 $("span:first").text("( e.pageX, e.pageY ) : " + pageCoords);
 $("span:last").text("( e.clientX, e.clientY ) : " + clientCoords);

 var sideMenu = $('.side-menu');

 if (e.pageX < 100 && $('.side-menu').is(":visible")){
    console.log('make visible');
    sideMenu.animate({"left":"-96px"}, 1000);

 }
 else if(!$('.side-menu').is(":visible")){
    sideMenu.animate({"left":"-96px"}, 1000);
    console.log('hide');

 } 

});

Upvotes: 0

Views: 345

Answers (3)

RestingRobot
RestingRobot

Reputation: 2978

It sounds like you just need to check if the menu is being shown. Try something like

 $("#gridcontainer").mousemove(function(e){

    var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
    var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
    $("span:first").text("( e.pageX, e.pageY ) : " + pageCoords);
    $("span:last").text("( e.clientX, e.clientY ) : " + clientCoords);

    var sideMenu = $('.side-menu');

    if (e.pageX < 100 && $('.side-menu').is(":visible")){
       console.log('make visible');
       sideMenu.show();
       sideMenu.animate({"left":"-96px"}, 1000);

    }
    else if(!$('.side-menu').is(":visible")){
       sideMenu.animate({"left":"-96px"}, 1000);
       sideMenu.hide();
       console.log('hide');

     } 

You could even have your show() function do the animation for you. See here for some examples.

Upvotes: 1

Jack M.
Jack M.

Reputation: 1170

Perhaps you could put an invisible, absolute div to the left and use the mouseIn and mouseOut functions.

You could also add a class and only run the open code if the class is non-existent. Likewise with the close. Only run when the class exists.

You could also maybe do (e.pageX == 99) and else if (e.pageX == 101). In the else you run code similar to what you have now to make sure it closes/opens incase those numbers didnt register.

Upvotes: 0

Ryoku
Ryoku

Reputation: 822

You could add a toggle boolean variable that triggers when the event is activated and changes when the mouse moves back away from that side. Then just check with an if what's the status of that variable to see if you animate or not.

Upvotes: 0

Related Questions