1

after working on an interactive site that automatically navigates using ids in the url, I was wondering how to hide that while it will still navigate normally. After some research on here, I found the following script which doesn't work for me.

if ($.browser.msie  && parseInt($.browser.version, 10) === 9 && window.location.href.indexOf("#")) 
    {
        document.location.href = String( document.location.href ).replace( /#/, "" );
    }

ankit Chaudhary & jetpack pony answered my question, I just had concerns that were dealt with.

  • First, `$.browser` is deprecated for years now, and it's probably already removed from latest `jQuery`s. Second, the code only replaces the `#` mark, but not the hash content itself, which doesn't sound very useful. Please clarify your problem. – Zoltán Tamási Feb 07 '17 at 09:47
  • Please specify "doesn't work for me". What exactly does your snippet wrong and what should it do? – gus27 Feb 07 '17 at 09:55
  • It should hide the id from the url without compromising navigation between those elements with their ids. If I were to enter www.site.com/#home, it will take me to the home section and the url will read www.site.com. –  Feb 07 '17 at 10:00
  • This will help you http://stackoverflow.com/a/5298684/290343 – Ankit Chaudhary Feb 07 '17 at 10:03
  • 2
    Don't do that.. – Qwertiy Feb 07 '17 at 10:07

2 Answers2

0

You could use the pushState method to manipulate the URL without reloading/refreshing the page.

window.history.pushState(
    "object or string", 
    "Title",
    window.location.href.substring(0, window.location.href.indexOf('#'))
);
gus27
  • 2,616
  • 1
  • 21
  • 25
  • I'll keep that in mind next time. Can this be used more than once on the same target? –  Feb 07 '17 at 10:10
0

You are replacing only "#" symbol in your replace method. To replace the whole hash it should look like this:

.replace(/#.+$/, "");

Also, instead of document.location.href consider using HTML5 history API. It provides 2 methods:

pushState(): it changes the URL in the URL bar and creates a new history entry. For example if you are on a page example.com/#foo and you call history.pushState("", "", "example.com"), your URL bar will display example.com and when you press a browser back arrow, it will take you back to example.com/#foo.

replaceState(): it changes the URL in the URL bar and replaces a current history entry. Meaning that in the same example as above, browser back arrow will take you to a page before example.com/#foo.

Here is an example of your code using pushState():

var loc = window.location;
if (loc.hash) {
  history.pushState({}, document.title, loc.pathname + loc.search);
}

The browser support of this API is very good for details check: Browser compatibility

jetpackpony
  • 1,270
  • 1
  • 12
  • 22