A Working Javascript Back to Previous Page Link
In a recent project, I wanted to mimic the ‘back’ button of the browser using an on page link.
Replicating browser functions and unnecessary javascript are usually things you should avoid, but this was a special case. These were single pages that needed to be accessed from several different sections of a site and the ‘back to previous page’ link helped to keep the on-page navigation logical.
The problem was, I couldn’t find a version of the code which worked consistently across browsers. I tried a number of combinations such as javascript:history.go(-1); and history.back();, in the href attribute, onclick event or in an external function, but many didn’t work at all or behaved differently in different browsers.
After wading through several search results pages listing other people with the same problem, Google provided a solution: www.irt.org/script/911.htm. It seems to work well (tested in FF 1.5 and IE 6).
The Solution:
Add the following code to a HTML page:<a href="go-back-javascript-error.htm" onClick="this.href='javascript:GoBackLink()'" title="Go back to the previous page">« Go Back</a>
(go-back-javascript-error.htm is a page that will be shown if the javascript doesn’t work. It explains that the user should use the back button instead.)
Add the following code to the javascript file:
// go back to previous page function
function GoBackLink() {
history.back();
}
I don’t know why this particular code works in an external function. Maybe a passing javascript expert will be kind enough to leave a comment to explain….
Posted September 11, 2007
Comments(0)
