"window.location.hash = location.hash" does not work in Webkit (Safari & Chrome)

I cannot get window.location.hash = location.hash to work in Safari.

I use javascript to wrap the contents of my page with a scrollable DIV, located under the navigation bar on my web page. Since the scrollbar location gets reset when javascript starts up, I lose the original hash location that sets the URL. I need to re-specify the hash location without reloading the page using javascript, so I use window.location.hash = location.hash . It works in IE8, Firefox, and Opera, but it does not work in Safari. (I will also consider Chrome, but I have not tested it). Any suggestions?

Hint: I like jQuery.

+7
source share
5 answers

Webkit has two oddities that prevent window.location.hash = location.hash from working properly.

  • Webkit responds to window.location.href instead of window.location.hash (like all other browsers). Curiously, webkit can still read the hash URL tag using location.hash
  • Webkit has a reported error where href location must be installed in the same place twice before the browser moves to a new location. Error report here .

This code solved my problem: (using jQuery).

 $(document).ready(function() { gotoHASH() }; function gotoHASH() { if (location.hash) { if ( $.browser.webkit == false ) { window.location.hash = location.hash; } else { window.location.href = location.hash; } } }; 
+11
source

I finished with

 window.location.hash = ""; window.location.hash = "myanchor"; 

This worked fine in all the desktop browsers that I tested on iOS and Android Chrome. i /

+5
source

First set location.hash to something else and return it right away.

 var t = window.location.hash; window.location.hash = "non-existant-id"; window.location.hash = t; 
0
source

Before JavaScript changes the initial position of the hash, find the scroll position using

 var st = $(window).scrollTop(). 

If you want to restore the scroll location, use

 $(window).scrollTop(st); 
0
source
 go_hash('#home') 

Function...

 function go_hash(hash) { console.log('go_hash: ' + hash) if(hash.indexOf('#') == -1) hash = '#' + hash if(document.location.hash) { document.location.hash = hash return } if(window.location.hash) { window.location.hash = hash return } if(document.location.href) { document.location.href = hash return } window.location.href = hash } 
0
source

All Articles