var Scroller = (function(){ var Scroller = {} var prev, next var webkitRatio = 1 Scroller.init = function(opt){ previous = opt.previous next = opt.next if (is_mobile) { // document.body.addEventListener("touchstart", touchstart) // document.body.addEventListener("touchmove", touchmove) // document.body.addEventListener("touchend", touchend) } else { document.body.addEventListener("wheel", wheelDelta) document.body.addEventListener("keydown", keydown) } } var touching = false, touchStartTime, touchStartY, touchEndY, touchDist, touchScrollTop function touchstart (e) { touching = true touchStartTime = +(new Date) touchStartY = touchEndY = e.touches ? e.touches[0].pageY : e.pageY } function touchmove (e) { if (! touching) return e.preventDefault() var timestamp = +(new Date) var duration = timestamp - touchStartTime touchEndY = e.touches ? e.touches[0].pageY : e.pageY touchDist = touchStartY - touchEndY } function touchend (e) { if (! touching) return e.preventDefault() touching = false var timestamp = +(new Date) var duration = timestamp - touchStartTime touchDist = touchStartY - touchEndY if (Math.abs(touchDist) < 10 || duration < 100) { step(1) } else { touchDist > 0 ? step(1) : step(-1) } } function wheelDelta (e){ e.preventDefault() var deltaY = 0 // WebKit if ( e.deltaY ) { deltaY += e.deltaY * webkitRatio } else if ( e.wheelDeltaY ) { deltaY += e.wheelDeltaY * webkitRatio } // Opera / Explorer 9 else if ( e.wheelDelta ) { deltaY += e.wheelDelta * webkitRatio } // Firefox else if ( e.detail ) { deltaY -= e.detail * 2 } wheel(deltaY) } var lastScrollEvent = +new Date(), lastDY = 0, lastSign = 0 function wheel (dy) { if (isNaN(dy)) return var now = +new Date(), newSign = sign(dy) if ((now > lastScrollEvent + 300) || (lastSign !== newSign && Math.abs(dy) > Math.abs(lastDY*2)) || (lastSign === newSign && Math.log(Math.abs(dy)) > 1+Math.log(Math.abs(lastDY)))) { step(sign(dy)) } lastDY = dy lastSign = newSign lastScrollEvent = now } function step (n) { var now = +new Date() if (now < lastScrollEvent + 300) { return } lastScrollEvent = now if (n < 0) { previous() } else { next() } } function keydown (e) { // console.log(e.keyCode) switch (e.keyCode) { case 32: // space e.preventDefault() step(1) break case 36: // home e.preventDefault() break case 35: // end e.preventDefault() break case 33: // page up case 38: // up e.preventDefault() step(-1) break case 34: // page down case 40: // down e.preventDefault() step(1) break } } return Scroller })()