views:

340

answers:

2

Is there a way to scroll or jump down a page after rendering it?

Specifically, in my controller action, there are some situations where I'll want to send the user to a particular place on the page. If it were just a link from another page, I'd probably use a URI fragment identifier - "http://blorg.com/page#id" - but this needs to be dynamically generated depending on some condition.

Maybe I need to use JavaScript (Prototype) somehow, but I don't know how to call the function once the page is done loading, especially from the controller.

Thanks.

+3  A: 

You should really do this type of thing in your view. In your controller you should evaluate your condition to determine the part of the page you want to show, then pass the result into the view. You can then be able to use this information in your view to add a small piece of javascript at the bottom of the page that does something like the following. Of course this doesn't help you if the user has javascript turned off ;)

Controller code:

def index
  # evaluate the condition
  @section = (rand*10).to_i
end

View view code:

<div id="#section1">some stuff</div>
....
<div id="#section9">other stuff</div>

<% if @section>0 %>
<script type="text/javascript">
// <!--
document.location.hash="#section<%= @section %>";
// -->
</script>
Daniel
That's a good point! Thanks Daniel.
Raphomet
A: 

you can have browser scroll to a position down the page by including a fragment part in the url that links to the page. e.g. http://example.com/index.html#section3 will scroll the page to the element with 'id' section3. you can use that id on a link, paragraph, etc. the browser will make sure the element is visible after the rendering.

Vitaly Kushner