I want to know when the user scroll in my webpage. How do I create an Elm event after each time a user scrolls?
I want to know when the user scroll in my webpage. How do I create an Elm event after each time a user scrolls?
The easiest way is to create an event listener on the div. Use the Html.Events on to create a custom event listener.
That html event then needs to be decoded into an Elm event. like this:
on "wheel" (Decode.succeed Scroll) where Scroll is a Msg, it can be any of you app's Msgs. This can be applied to any div. For example here is an implementation with Elm-UI to detect a scroll anywhere in the webpage.
import Html.Events exposing (on)
import Json.Decode as Decode
view model =
layout
[ htmlAttribute <| on "wheel" (Decode.succeed Scroll)
]
<|
column []
[
~~~ snip
]
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.