Removing a fragment identifier from the address bar

Hi, hope someone can help. I want to hide the fragment identifier from the address bar, and instead:

www.mydomain.com/example.html#something

I just get:

www.mydomain.com/example.html

when I click on the anchor tag.

I reviewed a lot of related questions and forums, but still can't figure it out. I am sure I should use something like:

window.location.href.replace(/#.*/,''); //and or .hash 

just can't understand.

The localScroll plugin allows you to hide or save identifiers, and by default they are hidden. I think many gallery plugins have a similar option.

but when I try to do it myself (a novice bit), I get a crazy result.

below is some basic example script I would like it to work with:

 <style> .wrap{ width:300px; height:200px; margin:auto; } .box{ width:300px; height:200px; position:absolute; display:none; } #one{background:red;} #two{background:blue;} #three{background:green;} .load{display:block;} </style> <body> <ul> <li><a href="#one">One</a></li> <li><a href="#two">Two</a></li> <li><a href="#three">Three</a></li> </ul> <div class="wrap"> <div id="one" class="box load">This is Box 1</div> <div id="two" class="box">This is Box 2</div> <div id="three" class="box">This is Box 3</div> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script> $(document).ready(function() { $("ul li a").click(function(){ $("div.box").fadeOut(1000); $($(this).attr('href')).fadeIn(1000); }); }); </script> </body> 
+8
javascript jquery
source share
3 answers

Add

 return false; 

at the end of your click function, this will stop the propagation of this event

+19
source share

the replace function returns a new line; it does not work on the old one. You need to use: window.location.href = window.location.href.replace(/#.*/,'') .

However, this will not have the expected effect, since changing window.location.href in any way is not just adding or changing a hash tag, the page will reload.

The localScroll plugin works by searching for the hashtag and using the jQuery scrollTo plugin to scroll to the location and prevent the default browser behavior when clicking on the hash tag link. They did not actually change the URL to remove the hash; they prevented it from appearing.

The best thing you can do if you want to remove the hash from the URI is to save only # at the end:

 window.location.href = window.location.href.replace(/#.*/,'#'); 

Although in some older browsers even this will lead to a reload of the page (albeit very old browsers).

+3
source share

try this .... it will remove # globally in your url

 window.location.href.replace(/\#*/g, "") 

here demo

-one
source share

All Articles