How to Scroll to a Position in Bucklescript

Since Bucklescript-TEA doesn’t support scrolling, or at least not that I’m aware of, you’ll need to do it with interop with Javascript.

In my case, I wanted to be able to scroll to a certain element and then scroll back to the top of the page as well when we navigate to a new page.

So let’s handle the first scenario - Scolling to an element.

We need to first get the element:

type doc
external document = doc = "" [@@bs.val]
external querySelector : doc -> string -> dom_element = "" [@@bs.send]
let element = document |. querySelector("#id-selector")

Then we can use the scrollIntoView method on elements:

Here we setup the interop with external for scrollIntoView:

type dom_element = Dom.element Js.Nullable.t
external scrollIntoView : dom_element -> unit = "" [@@bs.send]

And here’s the code to scroll to an element

let element = document |. querySelector("#" ^ position) in
  if element <> Js.Nullable.null then
    element |. scrollIntoView;

Which gives you Javascript that looks like this:

var element = document.querySelector("#" + position);
  if (element !== null) {
    element.scrollIntoView();

2nd: We want to be able to scroll to top of the page

We setup an external interop for scrollTo:

external scrollTo : int -> int -> unit = "" 
[@@bs.val][@@bs.scope "window"]

Then we just use it like this:

scrollTo 0 0

Which gives us the Javascript that looks like this:

window.scrollTo(0, 0);

Simple, right?

Comments