views:

1629

answers:

4

Using JavaScript, is there a way to update window.location.hash without scrolling the web page?

I have clickable title elements that toggle the visibility of a div directly beneath them. I want the /foo#bar in the history when clicking titles but don't want the page scrolling about. So when navigating away from /foo#bar I'll be able to use the back button and have the div whose ID is in window.location.hash be visible upon return.

Is this behavior possible?

+3  A: 

This behavior is very much possible. You should look into some of the libraries that have been developed to give you this functionality.

Really Simple History: http://code.google.com/p/reallysimplehistory/ SWFAddress: http://www.asual.com/swfaddress/

Willem
Great. Those look good except for the existent documentation for RSH. I think SWFAddress looks like the best option for now.
Jonathon Watney
Indeed. I feel that there is a lack of documentation of RSH. I use SWFAddress and so far it has worked just fine.
Willem
+2  A: 

See this stackoverflow question and/or this page where I present a basic script to address the problem.

KooiInc
Thanks. I've checked out that question and your custom script.
Jonathon Watney
+1  A: 

Another thing you could try is changing the id of the element the hash points to temporarily. Worked for me!

function changeHashWithoutScrolling(hash) {
  var id = hash.replace(/^.*#/, ''),
      elem = document.findById(id)
  elem.id = id+'-tmp'
  window.location.hash = hash
  elem.id = id
}
Sunny
This is awesome. Works great.
samg
+1  A: 

As easy as it get

var scrollmem = $('body').scrollTop()
window.location.hash = hash;
$('html,body').scrollTop(scrollmem)
Catherine
This works great, thanks!
Sam