43

I'm designing a very simple web page (HTML only), the only "feature" I want to implement is to do something when the user scrolls down the page, is there a way to capture that "event" somehow?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Artemix
  • 8,497
  • 14
  • 48
  • 75

13 Answers13

45

If you don't want to use jQuery (which you might not do for a very simple HTML page), you can accomplish this using regular Javascript:

<script>
function scrollFunction() {
    // do your stuff here;
}

window.onscroll = scrollFunction;
</script>

You mentioned that you wanted to do something when they scroll down the page - the onscroll event fires off scrolling in any direction, in either the x- or y-axis, so your function will be called any time they scroll.

If you really want it to only run your code when they scrolled down the page, you'd need to preserve the previous scroll position to compare against whenever onscroll gets called.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • 5
    Should use `attachEvent` (IE) and `addEventListener` (everything else) probably instead of `onscroll`. – crush Jan 02 '14 at 22:00
  • @crush, Why use attachEvent and addEventListener instead of onscroll? – Pacerier Apr 30 '14 at 14:56
  • 2
    @Pacerier Okay, let me revisit this comment because it's misleading, and based on faulty information that I obtained and is being propagated around the Internet. According to the [W3C HTML5 specification](http://www.w3.org/TR/html5/webappapis.html#event-handlers-on-elements,-document-objects,-and-window-objects), there is nothing wrong with using `onscroll`. It is important to note that `onscroll` specifically, did not exist in the [HTML4 specification](http://www.w3.org/TR/html4/interact/scripts.html#h-18.2.3). – crush Apr 30 '14 at 15:48
  • 2
    I will say that the benefit of using `addEventListener` and `attachEvent` is that you can attach multiple events, rather than assigning a single event. It makes the events more manageable. I'm not sure how you'd do this with the `onscroll` property. (I was unable to find a way) – crush Apr 30 '14 at 15:59
  • It's also less risky to cause bugs using addEventListener, because if there was already a function set in the onscroll property, replacing it with your own function will cause the previous function not to be executed any longer when scrolling, and this will surely negatively impact the behavior of the code that had put its function there before you. – sboisse Aug 01 '14 at 19:43
  • @crush: You can chain the old event listener: `var old = window.onscroll; window.onscroll = function() { /* do my thing */ if (typeof old == "function") old();}` This is all a kludge however, so the best way is to use `addEventListener` – Stijn de Witt Aug 08 '14 at 12:36
  • `onscroll` would overwrite any and all scripts using the `scroll` event. It's widely discouraged unless you have a good reason for not using `addEventListener`. – Chris Hayes Oct 14 '20 at 21:17
31

A better way is to not only check for scroll events but also for direction scrolling like below;

$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
    console.log('Scroll up');
}
else {
    console.log('Scroll down');
}
});
Joe Ng'ethe
  • 874
  • 2
  • 12
  • 26
24

Just for completeness, there's another solution using another JS framework (Mootools)

window.addEvent('scroll',function(e) {
    //do stuff
});
Sean Fujiwara
  • 4,506
  • 22
  • 34
stecb
  • 14,478
  • 2
  • 50
  • 68
  • 6
    Why not using `window.addEventListener("scroll", function(e) {...});`? Because of the extra 8 letters? – Iulian Onofrei Mar 13 '14 at 14:56
  • 2
    Because in that way (mootools' way) you support(ed) also IE < 9 (attachEvent stuff) ... – stecb Mar 15 '14 at 11:25
  • So it's modifying `window`'s `prototype`? – Iulian Onofrei Mar 16 '14 at 23:46
  • 3
    Yes it is modifying window's prototype and there is no problem doing so. It is Javascript's nature to extend prototypes and there are just a few cases where you should be really careful (like Object or DOM-Elements). – inta Apr 13 '14 at 21:58
  • Any function declared at global scope is made part of the `window` object. – crush Apr 30 '14 at 15:41
23

You can't do it with just HTML, you'll need to use Javascript. I recommend using jQuery, so your solution can look like this:

$(document).ready(function() {
    $(window).scroll(function() {
      // do whatever you need here.
    });
});

If you don't want or are unable to use jQuery, you can use the onscroll solution posted by Anthony.

Chuck Callebs
  • 16,293
  • 8
  • 56
  • 71
  • I guess he is looking for only scroll down not scroll up. is there anything for scroll down only. –  Dec 15 '15 at 05:36
7

For capturing mouse wheel event since mousewheel event is Deprecated and Non-standard you can use wheel event instead. You can read the documentation here

window.onwheel = e => {
  if(e.deltaY >= 0){
    // Scrolling Down with mouse
    console.log('Scroll Down');
  } else {
    // Scrolling Up with mouse
    console.log('Scroll Up');
  }
}
Kia Abdi
  • 77
  • 1
  • 6
  • 2
    https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event Note: Don't confuse the wheel event with the scroll event. The default action of a wheel event is implementation-specific, and doesn't necessarily dispatch a scroll event. Even when it does, the delta* values in the wheel event don't necessarily reflect the content's scrolling direction. Therefore, do not rely on the wheel event's delta* properties to get the scrolling direction. Instead, detect value changes of scrollLeft and scrollTop of the target in the scroll event. – plusz Sep 15 '21 at 09:30
4

Here is my solution in pure JavaScript, be careful the only problem is that it is executed a lot of times. Sorry for the spelling I use google translate, I am french ;)

var scrollBefore = 0;

window.addEventListener('scroll',function(e){
    const scrolled = window.scrollY;

    if(scrollBefore > scrolled){
        console.log("ScrollUP");
        scrollBefore = scrolled;
        //Desired action
    }else{
        scrollBefore = scrolled;
        console.log("ScrollDOWN");
        //Desired action
    }

})
Al3xD3v
  • 41
  • 1
3

u can simply use this

window.addEvent('scroll',function(e) {
    if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
            // enter code here
        }
});
S.Saderi
  • 4,755
  • 3
  • 21
  • 23
3

above answers are correct. Here's the vanilla Javascript approach.

document.addEventListener("mousewheel", function(event){
  if(event.wheelDelta >= 0){
    console.log("up")
  }else{
    console.log("down")
  }
})

Update: Deprecated

https://developer.mozilla.org/en-US/docs/Web/API/Element/mousewheel_event

Min Somai
  • 567
  • 6
  • 13
  • 2
    Although this code might solve the problem, a good answer should also explain **what** the code does and **how** it helps. You can use the edit link below your answer to improve the post. – BDL Oct 19 '20 at 12:58
1

This works for me.

var previousPosition

$(window).scroll(function(){
  var currentScrollPosition=$(window).scrollTop() + $(window).height()
  if (currentScrollPosition>previousScrollPosition) {
    console.log('down')
  }else if(currentScrollPosition<previousScrollPosition){
    console.log('up')
  }
  previousScrollPosition=currentScrollPosition
});
Alvin Lau
  • 194
  • 2
  • 9
0
/**
 * This function will determine if a client mousewheel is scrolling up or down.
 */
  //window.addEventListener("load", eScroll);

  function eScroll() {

      window.addEventListener('mousewheel', (event)=> {

        let originalEvent = event.wheelDeltaY;

        if (event.wheelDeltaY >= 0) {
            console.log('Scroll up');
        }
        else {
            console.log('Scroll down');
        }
    });
  }

  window.addEventListener("load", scrollDown);

  function scrollDown() {

      window.addEventListener('mousewheel', (event)=> {

     if (event.wheelDeltaY <= 0) {
        console.log(event.wheelDeltaY);
        console.log('Mousewheel has scrolled down');
      }
   })
  }

  window.addEventListener("load", scrollUp);

  function scrollUp() {

      window.addEventListener('mousewheel', (event)=> {

      if (event.wheelDeltaY > 0) {
        console.log(event.wheelDeltaY);
        console.log('Mousewheel has scrolled up');
      }
  })

  }
ha100
  • 1,563
  • 1
  • 21
  • 28
darrell
  • 63
  • 1
  • 4
0

Check if the user scrolled up and simply return

window.addEventListener(
  "scroll",
  e => {
    const scrolled = window.scrollY; // Number of pixels the user has scrolled
    let lastScrolled = 0; // Number of pixels the user has scrolled in the last event

    // If the user scrolls down, the scrolled value goes up and vice versa
    // So basically
    if (scrolled < lastScrolled) {
      // Then the user scrolled up!
      console.log("GET OUT! YOU SCROLLED UP!");
      // But you should update the lastScrolled value nonetheless
      lastScrolled = scrolled;
      return; // And then get out!
    }
    lastScrolled = scrolled; // The value gets updated in any case
    // And your code goes here
  },
  false
);


0

this code works for me, i hope this help you to

var scrollval = 0;
window.addEventListener('scroll', () => {
  if(scrollval > window.scrollY) {
    // Do something
    console.log('Scroll up')
  } else {
    // Do something
    console.log('Scroll down')
  }
  scrollval = window.scrollY;
});
Rian
  • 1
  • 1
0

Regarding this comment https://stackoverflow.com/a/63997400/9654048 This code should no repete more than once per direction Edit values and use it :)

const element = document.querySelector('nav');


element.style.lineHeight = '100px';
element.style.height = '100px';

// scroll tracking
let lastScrollY = window.scrollY;
let scrollingDown = false; // Tracking scroll down
let scrollingUp = false; //  Tracking scroll up


function handleMouseWheel(event) {
  const currentScrollY = window.scrollY;

  if (currentScrollY > lastScrollY && !scrollingDown && window.innerWidth > 991) {
    //Scroll down ( trigers only onece)
    scrollingDown = true;
    scrollingUp = false;

    element.style.lineHeight = '50px';
    element.style.height = '50px';
    //console.log("TEST down");
  } else if (currentScrollY < lastScrollY && !scrollingUp) {
    //Scroll up ( trigers only onece)
    scrollingUp = true;
    scrollingDown = false;

    element.style.lineHeight = '100px';
    element.style.height = '100px';
   //console.log("TEST up");
  }

  lastScrollY = currentScrollY;
}

// calling event
window.addEventListener('wheel', handleMouseWheel);
M.Nikolic
  • 1
  • 1