scroll events under Javascript
Recently, I write an single page site like slides. It use some keyboard,mouse wheel events.
And I use Jquery as my tool.
once you have bind the event, remain things is easy. you just margin or padding the content area 100%, or go to target anchor.
$ ( 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 once you are in input area
Jquery also provide keypress
, keyup
, focusout
these related methods.
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 duplicate 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
}
} ) ;
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 scrollNext = function ( ) {
var oldPos = 0 ;
var pos = $ ( window ) . scrollTop ( ) ;
if ( pos > oldPos ) {
//next
}
if ( pos > oldPos ) {
//prev
}
oldPos = pos ;
}
$ ( window ) . scroll ( scrollNext ) ;