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.
$ ( 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.
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
}
} ) ;
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 ) ;
there are some open source plugins easy to realize the scroll effect.