views:

357

answers:

3

Hey I'm calling history.back() on the on-click of a 'back' button in a rails app. But nothing happens. There is history in the browser -- pressing the browser's back button takes me back to the correct page.

If I use history.go(-2) however, the page goes back correctly. So why do I have to tell javascript to go back two pages instead of one?

Any ideas how to debug this?

I tried this in FF and Safari.

Thanks!

--Additional Info:

Ok I played around some more and this works:

<a href='javascript:' onclick='history.back();'>

Originally, the code was:

<a href='#' onclick='history.back();'>

What's the difference? (Note that this used to work before, something has changed which makes the latter link not work)

A: 

have you tried adding return false? So:

<a href='#' onclick='history.go(-1);return false;'>
Andrew G. Johnson
yes adding 'return false' fixed it! Thx. So is this the recommended approach?
Hisham
I always try to avoid "back" buttons since by nature they are unpredictable, however if your question is more specific about return false, then it should always be used when you want to run javascipt and then not perform the actual action (in this case "click") because what your code said was "go back a page, then go to currentpage.html#" which was your issue
Andrew G. Johnson
A: 

If you use link_to_function it will automatically add return false to the end.

<%= link_to_function "Go back", "history.back()" %>
ryanb
A: 

I'd recommend using <%= link_to :back %>. Read more here: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M002142

Ebrahim