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.

1
  • 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 5, 2012 at 2:45

1 Answer 1

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");
});
6
  • 4
    Don't use w3schools... w3fools.com (Alternative link for info on window.location: developer.mozilla.org/en/DOM/window.location) Feb 5, 2012 at 2: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 :) Feb 5, 2012 at 2:48
  • 1
    Thanks for actually fixing it. +1 for your trouble :-) Feb 5, 2012 at 3: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 5, 2012 at 3: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). Feb 5, 2012 at 3:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.