3

Is it possible to get the root page scroll to an anchor link when it loads the first time?

in my routes.rb file, i did

root :to => 'home#index#header' (#header being the anchor element in the index.html.erb)

But, obviously, that did not work.

curiousCoder
  • 192
  • 1
  • 17
  • `routes.rb` only specifies the controller and action to use, so you wouldn't specify the anchor there. – Chloe Sep 10 '17 at 20:29

2 Answers2

0

You could do that in your controller by passing an :anchor parameter to any URL helper. See How do you use anchors for IDs in routes in Rails 3? for a nice example.

You could also do that via javascript directly in the view (where it belongs IMO).

So no, I don't know a way to do that in your routes.rb but even if I did I would suggest against it. In your routes you are wiring incoming requests to controllers and actions. An HTML anchor is a view-related thing so it doesn't belong to routes.rb.

Community
  • 1
  • 1
Kostas Rousis
  • 5,918
  • 1
  • 33
  • 38
  • 1
    yeah i am aware of d :anchor parameter, but i like to know a method which will allow the root page, when first loaded, to scroll n show the anchor element – curiousCoder May 14 '14 at 11:15
  • I proposed two alternative methods in my answer. Via a controller (with a redirect - render doesn't seem to accept an :anchor) or in the view itself. – Kostas Rousis May 14 '14 at 11:17
0

Use Javascript: (actually Coffeescript):

$(document).on 'turbolinks:load', ->
  window.location.hash = '#my_anchor'
Chloe
  • 25,162
  • 40
  • 190
  • 357