Eric Di Bari
Eric Di Bari

Reputation: 3867

Back button - skip anchors

I have a typical ajax-style dynamic content setup: click a link, change anchor in address bar, and load new content. When user clicks the back button, it cycles through all the anchors - as expected.

Is there a way (using JavaScript I'm assuming) to make the back button go to the previous page, and 'ignore' all the anchors?

Upvotes: 3

Views: 4393

Answers (3)

th_lo
th_lo

Reputation: 575

location.replace(document.referrer)

this works for me. depending on your purpose, you can use it in the "onclick" or add some additional conditions via JavaScript e.g. if the referrer is empty See: In what cases will HTTP_REFERER be empty

Upvotes: 0

Naor
Naor

Reputation: 24083

Count the stages the user pass and use

history.back(X);

or

history.go(-1*X);

in order to go back X pages/anchors.

Upvotes: 5

Oscar Godson
Oscar Godson

Reputation: 32726

First, to make sure Im understanding, you have named your AJAX bookmarks the same as IDs in your DOM elements? If so, anyway to undo this? You can trick it not to go down, but this is kludgy way of doing it. Instead you should have a ID like #somepage and AJAX urls like #!/somepage this way they don't get confused. Also, people like Google will not know normal #ids are hash URLs, but doing #!/ gives Google a clue.

Now, if you want to do it using a #!/ method you need a timer for older browsers (<=IE7) But for "modern" browsers IE8, FF, and Chrome you can use the onhashchange JS property like:

window.onhashchange = function(){ console.log('hash has changed') };

Then, if you want to support older browsers you need to do something a little more advanced. You need to do:

var currentPage = '';
setTimeout(function(){
  if(currentPage !== window.location.hash){
    console.log('hash has changed');
    currentPage = window.location.hash
  }
},500);

In both examples you need to replace the console.log()s with a function of your own that triggers the "change page" event.

To stop the scrolling you could add:

window.onhashchange = function(){
  if (window.location.hash == "" || window.location.hash == "#"){ return false; }
  //rest of your code here!
};

The return false will prevent the scrolling. This should work in the timer as well.

More Information:
https://developer.mozilla.org/en/DOM/window.onhashchange
http://msdn.microsoft.com/en-us/library/cc288209(VS.85).aspx
http://ajaxpatterns.org/Unique_URLs

Upvotes: 1

Related Questions