Document and Browser events in 0.19

Hello,

For a particular application I needed to listen for scroll events on the main document. To do this I searched this forum and found the following post: Elm-Scroll - An Effect Manager for Scroll Events

In a comment, user ilias suggests a ports based solution, and even demonstrated it using ellie: https://ellie-app.com/qqp6pVJRQa1/0

A slight variation of this worked perfectly for what I was attempting to do. But in that comment ilias suggests that in the next release there would be a pair of functions onWindow and onDocument to subscribe to events from the window and the document respectively.

So my question is first of all, am I correct that this pair of functions onWindow and onDocument never made it into the 0.19 release?

Secondly, assuming that to be the case, is the approach suggested by the linked ellie instance (https://ellie-app.com/qqp6pVJRQa1/0) roughly the correct one?

To save you visiting the link, the approach briefly (for a ‘wheel’ event) is:

port onWheel : (Value -> msg) -> Sub msg

wheelDecoder : Decoder Model
wheelDecoder =
    Decode.map2 Model
        (Decode.field "deltaX" Decode.float)
        (Decode.field "deltaY" Decode.float)


subscriptions : model -> Sub Msg
subscriptions _ =
    onWheel
        (\val ->
            case Decode.decodeValue wheelDecoder val of
                Ok model ->
                    Wheel model

                Err _ ->
                    NoOp
        )

Then in your index.html (or index.js):

var app = Elm.Main.init()
document.addEventListener("wheel", app.ports.onWheel.send);

Elm 0.19 did some reshuffling of what is part of which library, and how they all are called.

I think the behaviour you are talking about is now part of elm/browser 's Browser.Dom and Browser.Events modules.

1 Like

Thanks. That’s certainly where I looked. I don’t think it has anything corresponding to onDocument or onWindow, so unless I’m not understanding something, there isn’t a way, using those modules, to listen for events on the window or document.

Hm. I think it might be worth opening an issue on the GitHub repository of elm/browser; someone will probably see your message quicker there, and might be able to provide info on why it does not corrently exist, or how to do what you want to do. (Or maybe realize that they indeed are missing and super useful, and add them).

1 Like

It seems like you should be able to use the information from Browser.Dom getViewport to detect scroll events, though I’m not sure what the implementation would look like exactly.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.