Detect if user scrolls

How can I detect in javascript if the user scrolls?

+52
javascript
May 15 '12 at 16:39
source share
3 answers

it works:

window.onscroll = function (e) { // called when the window is scrolled. } 

edit:

You said that this is a function in TimeInterval ..
Try to do it like this:

 userHasScrolled = false; window.onscroll = function (e) { userHasScrolled = true; } 

then inside your interval paste this:

 if(userHasScrolled) { //do your code here userHasScrolled = false; } 
+55
May 15, '12 at 16:40
source share

You just said javascript in your tags, so the @Wampie Driessen post might help you.

I want to contribute as well, so you can use the following when using jQuery if you need it.

  //Firefox $('#elem').bind('DOMMouseScroll', function(e){ if(e.detail > 0) { //scroll down console.log('Down'); }else { //scroll up console.log('Up'); } //prevent page fom scrolling return false; }); //IE, Opera, Safari $('#elem').bind('mousewheel', function(e){ if(e.wheelDelta< 0) { //scroll down console.log('Down'); }else { //scroll up console.log('Up'); } //prevent page fom scrolling return false; }); 

Another example:

 $(function(){ var _top = $(window).scrollTop(); var _direction; $(window).scroll(function(){ var _cur_top = $(window).scrollTop(); if(_top < _cur_top) { _direction = 'down'; } else { _direction = 'up'; } _top = _cur_top; console.log(_direction); }); });​ 
+8
May 15 '12 at 16:58
source share
 window.addEventListener("scroll",function(){ window.lastScrollTime = new Date().getTime() }); function is_scrolling() { return window.lastScrollTime && new Date().getTime() < window.lastScrollTime + 500 } 

Change 500 to the number of milliseconds after the last scroll event in which you think the user is no longer scrolling.

( addEventListener better than onScroll because the former can coexist well with any other code that uses onScroll .)

0
Sep 19 '18 at 21:36
source share



All Articles