Is there a way to subscribe to page scroll events?

363 views
Skip to first unread message

Rupert Smith

unread,
Feb 10, 2017, 7:58:21 AM2/10/17
to Elm Discuss
I could use Dom.Scroll to get the y-offset of the body (http://package.elm-lang.org/packages/elm-lang/dom/1.1.1/Dom-Scroll), using its 'x' and 'y' tasks. The trouble is I don't know when the body may have been scrolled since this is a task and not a subscription.

Is a subscription for this available somewhere? Or just write my own port it...

Rupert Smith

unread,
Feb 10, 2017, 9:57:09 AM2/10/17
to Elm Discuss
On Friday, February 10, 2017 at 12:58:21 PM UTC, Rupert Smith wrote:
I could use Dom.Scroll to get the y-offset of the body (http://package.elm-lang.org/packages/elm-lang/dom/1.1.1/Dom-Scroll), using its 'x' and 'y' tasks. The trouble is I don't know when the body may have been scrolled since this is a task and not a subscription.

Is a subscription for this available somewhere? Or just write my own port it...

Scott Mueller

unread,
Feb 10, 2017, 10:42:45 AM2/10/17
to Elm Discuss
Here's code for an onScroll function that can be used just like an Html.Events.onClick. Basically, you can always use a Decoder with Html.Events.on to listen to HTML events this way:

type alias ScrollEvent =
  { scrollHeight : Int
  , scrollPos : Int
  , visibleHeight : Int
  }

onScroll : (ScrollEvent -> msg) -> Html.Attribute msg
onScroll tagger =
  Html.Events.on "scroll" (Decode.map tagger onScrollJsonParser)

onScrollJsonParser : Decode.Decoder ScrollEvent
onScrollJsonParser =
  Decode.map3 ScrollEvent
    (Decode.at ["target", "scrollHeight"] Decode.int)
    (Decode.at ["target", "scrollTop"] Decode.int)
    (Decode.at ["target", "clientHeight"] Decode.int)
Reply all
Reply to author
Forward
0 new messages