why javascript history.back() toggles between two pages

JavaScript Add comments

I was working in a project where each page had a back button. Because of the designers design the back button was created using anchor tag <a> and as a programmer i thought of using the back button like the following in the anchor tag.

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

But what had happened when i press the back button after navigating to various pages was i got locked between the last two navigated pages. It kept toggling between the last visited page and the previous page where as it is supposed to go backward step by step.

So let us say i have navigated from page 1 to 10 and now i am in page 10. When i press the back button in page 10 i came to page 9. But when i pressed the back button in page 9 again it took me to page 10 instead of taking me to page 8. So this keeps happening until i changed the code to the following.

<a href='javascript:window.history.back();'>Back</a>

After modifying to the above code all went well. The back button press worked normal which took me from page 10 all the way to page 1 when i kept on pressing the back button.

and besides the given code there was a style applied to the anchor tag and that was just float right.

Is this an issue needed attention which is to be posted in a blog? I don’t think so but thought of talking to the people to see their responses. If people know why this peculiar behaviour then please post a note of a reply or a reference or whatever which could be of assistance to all people. :)

3 Responses to “why javascript history.back() toggles between two pages”

  1. bird Says:

    nice tip,thanks much

  2. Om Shankar Says:

    When you have a custom function bound to onclick (or any) event, two things happen when the event occurs-
    1. Browser’s native thingies
    2. The Custom bound function

    In the 1st case, your function is only attached to click event
    But the browser is also doing the native things which it is supposed to do on clicking a link

    In the second case however, you are actually overriding the default Browser thing by triggering the redirection in the href itself
    So, there is no new link set in windows history which can lock you down between pages

    I would also recommend 2 things:
    1. have a function (javascript: –function– ; ) instead of direct code and console.log(window.history) in that function before history.back, just to check the history object’s value in both cases
    2. you can also use history.go(-1)

  3. Ste Says:

    Thanks man, now putting the same code on href works, such a weird situation though…

Leave a Reply

Entries RSS