Search code examples
htmleventsscrollelmmousewheel

How do I create an Elm Lang event when scrolling?


I want to know when the user scroll in my webpage. How do I create an Elm event after each time a user scrolls?


Solution

  • You almost certainly want to use a port to create the scroll event. Wheel cacn have some strange side effects.

    It is also recommend to ignore some of the scroll events otherwise your website will generate thousands of events per minute. This is done with the ticking variable below and requestAnimationFrame. Change ticking > 5 to any int you would like depending on your desired responsiveness.

    var ticking = 0;
    window.addEventListener("scroll", function (event) {
        if (ticking > 5) {
          window.requestAnimationFrame(function() {
            app.ports.recvScroll.send();
            ticking = 0;
          });
        }
        ticking += 1;
    });
    

    recvScroll is the name of the port in the related elm code. But you can name it whatever you would like.