Skip to content

Instantly share code, notes, and snippets.

@spinpx
Last active January 22, 2016 15:26
Show Gist options
  • Save spinpx/92ba0f1613cd704c65b0 to your computer and use it in GitHub Desktop.
Save spinpx/92ba0f1613cd704c65b0 to your computer and use it in GitHub Desktop.
Scroll events under Javascript #JavaScript

scroll events under Javascript

  • Recently, I wrote an single page site like slides. It involves some keyboard,mouse wheel events.
  • Depend on Jquery.
  • once you have binded the event, remains is easy. just needs margin or padding the content area 100%, or jump to the target anchors.

Keyboard Event

$(document).keydown(function(e) {
   var tag = e.target.tagName.toLowerCase();
   switch(e.which) {
     case 38:
       if (tag != 'input' && tag != 'textarea') goPrev();
       break;
     default: return;
   }
})
  • notice that do not bind keyboard event while you are in input area
  • Jquery also provide keypress, keyup, focusout these related methods.

Mouse Wheel Event

  • There are three mouse wheel event in general:
    mousewheel
    IE9,Chrome,Safari,Opera
    DOMMousescroll
    Firefox
    onmousewheel
    IE6/7/8
  • you can add event separately by addEventListener, or use Jquery’s bind method.
  • also you should consider repeated events. you can use time period to avoid this situation.
$(document).bind('mousewheel DOMMouseScroll MozMousePixelScroll', function(event) {
  event.preventDefault();
  var delta = event.originalEvent.wheelDelta || -event.originalEvent.detail;
  if (delta < 0) { 
    //down
  } else {
    //up
  }
});

Mobile Touch Event

  • touchstart
  • touchmove

Windows Scroll Bar

  • this method can be use dependent rather than above three method which usually use together to deal with different part behavior.
  • If you are not a height 100% page. Key down/up, Mouse wheel, touch Down/up all can be convert to scroll the window.
  • I use Jquery’s scrollTop method to realize the effect. Addtionally, Jquery provide scroll, scrollLeft.
    obj.scrollTop()
    just return the vertical position of the scroll bar
    obj.scrollLeft()
    return the horizontal position of the scroll bar
    obj.scroll(func)
    the same as obj.bind(‘scroll’), trigger when you scroll
var oldPos = $(window).scrollTop;
var scrollNext = function() {
  var pos = $(window).scrollTop();
  if (pos >  oldPos) {
      //next
  } 
  if (pos >  oldPos) {
      //prev
  }
  oldPos = pos;
}

$(window).scroll(scrollNext);

Plugins

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment