6

For example, if an user is on http://example.com, then the user goes to http://example.com#comments. If the user clicks "back" on his browser, how can I make him "ignore" http://example.com and go directly to the URL that he visited before that?

I have jQuery loaded.

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
  • 2
    You'd have to block the click that got him to `#comments` in the first place, perhaps using a `preventDefault()` and use jQuery to scroll there instead. Otherwise, it all becomes part of the normal history. – Sparky Feb 05 '12 at 02:45

1 Answers1

12

Instead of having a link like:

<a href='#comments'>Link</a>

Use location.replace() to "overwrite" the record of http://example.com in the browser's history.

https://developer.mozilla.org/en/DOM/window.location

Example:

HTML:

<a id='commentsLink'>Link</a>

JavaScript:

$("#commentsLink").click(function(){
    window.location.replace("#comments");
});
Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
  • 4
    Don't use w3schools... http://w3fools.com (Alternative link for info on `window.location`: https://developer.mozilla.org/en/DOM/window.location) – Platinum Azure Feb 05 '12 at 02:46
  • @Platinum Azure - That was in the back of my mind when I posted the link, but laziness got the best of me. Thanks for setting me straight :) – Chris Laplante Feb 05 '12 at 02:48
  • 1
    Thanks for actually fixing it. +1 for your trouble :-) – Platinum Azure Feb 05 '12 at 03:03
  • "you win this time" :), I would try to change my vote as soon as I am able (in case I am, I really don't know entirely how SO works). Sorry to have deleted my prev comments, but I don't want to lower the IQ of the ppl reading this with my nonsenses... – ajax333221 Feb 05 '12 at 03:16
  • :). You can just click upvote and it will undo the downvote, unless SO has decided to lock in the vote (which it does after a certain period of time). – Chris Laplante Feb 05 '12 at 03:17
  • @SimpleCoder it is impossible now... it is locked until you edit – ajax333221 Feb 05 '12 at 03:18