Zaid-Ajaj / Feliz.Router

A router component for React and Elmish that is focused, powerful and extremely easy to use.
MIT License
78 stars 16 forks source link

Navigating to a Hashsign on a page with smooth scrolling #18

Closed heimeshoff closed 4 years ago

heimeshoff commented 4 years ago

I can't navigate to an anchor inside a page. I would like to navigate on my landingpage by scrolling to the anchored sections using Ids in my divs. But, clicking a href with "#mySection" routes to /#mysection. Is it possible to either integrate a navigateTo(hash) or to not route internal hashes?

Zaid-Ajaj commented 4 years ago

Hi Marco,

You could implement this using by matching against /#section/{sectionName} where you dispatch a command that does the scrolling by looking up the coordinates of the anchor tag containing {sectionName} and using window.scrollTo. I haven't tested this but it roughly looks like this:

open Browser.Dom

let update msg state = 
  match msg with 
  | UrlChanged [ "section"; sectionName ] ->
      let (coordX, coorY) = findSectionCoordinates sectionName
      state, Cmd.ofSub (fun _ -> window.scrollTo(coordX, coordY))

Here, the function findSectionCoordinates will search DOM for that anchor tag that contains an href with the input section name. The left property will be coordX and top property will be coordY. You will have to play with the values to see whether the numbers need an offset

heimeshoff commented 4 years ago

Thanks, that works for me <3