How use JQuery/Javascript to scroll down a page when the cursor at the top or bottom edge of the screen?

webDevAndEverythingElse picture webDevAndEverythingElse · Feb 2, 2012 · Viewed 10.3k times · Source

Simple, I just would like to have it so when a user is dragging an item and they reach the very bottom or top of the viewport (10px or so), the page (about 3000px long) gently scrolls down or up, until they move their cursor (and thus the item being dragged) out of the region.

An item is an li tag which uses jquery to make the list items draggable. To be specific:

I currently use window.scrollBy(x=0,y=3) to scroll the page and have the variables of:

  1. e.pageY ... provides absolute Y-coordinates of cursor on page (not relative to screen)
  2. $.scrollTop() ... provides offset from top of page (when scroll bar is all the way up, it is 0)
  3. $.height()... provides the height of viewable area in the user's browser/viewport
  4. body.offsetHeight ... height of the entire page

How can I achieve this and which event best accommodates this (currently its in mouseover)? My ideas:

  1. use a an if/else to check if it is in top region or bottom, scroll up if e.pageY is showing it is in the top, down if e.page& is in bottom, and then calling the $('li').mouseover() event to iterate through...
    1. Use a do while loop... this has worked moderately well actually, but is hard to stop from scrolling to far. But I am not sure how to control the iterations....

My latest attempt:

          ('li').mouseover(function(e) {

            totalHeight = document.body.offsetHeight;
            cursor.y = e.pageY;
            var papaWindow = window;
            var $pxFromTop = $(papaWindow).scrollTop();
            var $userScreenHeight = $(papaWindow).height();
            var iterate = 0;

            do {
                papaWindow.scrollBy(0, 2);
                iterate++;
                console.log(cursor.y, $pxFromTop, $userScreenHeight);
            }

            while (iterate < 20);
      });

Answer

webDevAndEverythingElse picture webDevAndEverythingElse · Feb 3, 2012

Works pretty well now, user just needs to "jiggle" the mouse when dragging items sometimes to keep scrolling, but for scrolling just with mouse position its pretty solid. Here is what I finally ended up using:

 $("li").mouseover(function(e) {

  e = e || window.event; var cursor = { y: 0 }; cursor.y = e.pageY; //Cursor YPos
  var papaWindow = parent.window;
  var $pxFromTop = $(papaWindow).scrollTop();
  var $userScreenHeight = $(papaWindow).height();

  if (cursor.y > (($userScreenHeight + $pxFromTop) / 1.25)) {

         if ($pxFromTop < ($userScreenHeight * 3.2)) {

                   papaWindow.scrollBy(0, ($userScreenHeight / 30));
             }
        }
  else if (cursor.y < (($userScreenHeight + $pxFromTop) * .75)) {

        papaWindow.scrollBy(0, -($userScreenHeight / 30));

        }

   }); //End mouseover()