Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if user is scrolling

Tags:

javascript

How can I detect in javascript if the user is scrolling?

like image 874
user1365010 Avatar asked May 15 '12 16:05

user1365010


People also ask

How can I tell if someone is scrolling?

To detect if a user is scrolling with JavaScript, we can watch for scroll events by adding event handlers. to add the userHasScrolled variable. Then we set the window. onscroll property to a function that runs when we scroll.

How do I know if my page is scrolled?

If you want to check whether the user has scrolled to the bottom of the page, you can use the scroll() jQuery event. The given code piece takes the top scroll of the window, so how much the page is scrolled down, it adds the height of the visible window and checks if it is equivalent to the height of the document.

How do I know if my scroll is at the top?

You can check if window. scrollY (the number of pixels the window has scrolled vertically) is equal to 0 . If you want to check if the window has been scrolled to its leftermost, you can check if window. scrollX (the number of pixels the window has scrolled horizontally) is equal to 0 .


2 Answers

this works:

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

edit:

you said this is a function in a TimeInterval..
Try doing it like so:

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

then inside your Interval insert this:

if(userHasScrolled) { //do your code here userHasScrolled = false; } 
like image 85
Wampie Driessen Avatar answered Oct 06 '22 01:10

Wampie Driessen


You just said javascript in your tags, so @Wampie Driessen post could helps you.

I want also to contribute, 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);     }); });​ 
like image 35
Oscar Jara Avatar answered Oct 06 '22 01:10

Oscar Jara