How can I detect in javascript if the user 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.
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.
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 .
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; }
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); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With