Webdoodles

April 10, 2007

Javascript Back Link

Filed under: Javascript, Navigation — ukmagician @ 9:41 am

I’ve recently had need to add on-page links to replicate the ‘back’ button in the browser.

Normally, I avoid using javascript for navigation in this way, but it seems like the best solution in this case. However, I couldn’t find a version of the code which worked consistently accross browsers.

Finally, result number 20 or so in Google (amongst many other pages with others asking about the same problem) turned up this page: www.irt.org/script/911.htm which seems to work well (tested in FF 1.5 and IE 6).

I’ve added the following function to the javascript file:

// go back to previous page function
function goBack() {
history.back();
}

And use the following code in the HTML:

<a href="#" onClick="this.href='javascript:goBack()'" title="Go back to the previous page">&laquo; Back to previous page</a>

Previously, I had tried using onclick="javascript:history.go(-1);" and onclick="history.back();", and a number of variations with the javascript in the href attribute or onclick event or in an external function, but none of them gave consistent results – most didn’t work at all.

If anyone understands enough about javascript to tell me why onClick="this.href='javascript:goBack()'" works, please leave a comment!

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.