Shannon
Shannon

Reputation: 570

Scroll mouse position based function

Basically, I'm trying to have an "auto scroll" option for my site, I've got the basis of it working, although it doesn't re scroll back if you move the mouse back to the left rather than the right.

I've been at this for over 3 hours now, no luck what so ever searching the net!

Here's what I have:

 $(document).mousemove(function(e){
    window.mouseXPos = e.pageX;
    window.mouseYPos = e.pageY; 
       var height = $(window).height() /2;
       if (window.mouseYPos < height){
        $('body,html').stop().animate({     
            scrollTop: window.mouseYPos
        },10 );
       }
       else{
        $('body,html').stop().animate({     
            scrollTop: -window.mouseYPos
        },10 );
       }    
    });

Upvotes: 0

Views: 1218

Answers (2)

skinnynerd
skinnynerd

Reputation: 693

It's possible that when the mouse moves to the left, it is moving off of the window, so it won't trigger the event. You would want to scroll to a point where the mouse is inside the window. Try

$(document).mousemove(function(e){
   window.mouseXPos = e.pageX;
   window.mouseYPos = e.pageY;
   $('body,html').stop().animate({
    scrollTop: window.mouseYPos-$('window').height()/2,
    scrollLeft: window.mouseXPos-$('window').width()/2
   },1000 );
});

Upvotes: 1

sdespont
sdespont

Reputation: 14025

Try to delay your animation after 100ms where the mouse is not moving to avoid the new animation starts after each mouse pixel moving

scrollDelayTimer = null;
$(document).mousemove(function(e){
       window.mouseXPos = e.pageX;
       window.mouseYPos = e.pageY;

       clearTimeout(scrollDelayTimer);
       scrollDelayTimer = setTimeout(function () {
          scrollDelayTimer = null;
          $('body,html').stop().animate({
              scrollTop: window.mouseYPos,
              scrollLeft: window.mouseXPos
          },1000 );
       },100);
});

Upvotes: 1

Related Questions