views:

5569

answers:

4

Background: I have an HTML page which lets you expand certain content. As only small portions of the page need to be loaded for such an expansion, it's done via JavaScript, and not by directing to a new URL/ HTML page. However, as a bonus the user is able to permalink to such expanded sections, i.e. send someone else a URL like

http://example.com/#foobar

and have the "foobar" category be opened immediately for that other user. This works using parent.location.hash = 'foobar', so that part is fine.

Now the question: When the user closes such a category on the page, I want to empty the URL fragment again, i.e. turn http://example.com/#foobar into http://example.com/ to update the permalink display. However, doing so using parent.location.hash = '' causes a reload of the whole page (in Firefox 3, for instance), which I'd like to avoid. Using window.location.href = '/#' won't trigger a page reload, but leaves the somewhat unpretty-looking "#" sign in the URL. So is there a way in popular browsers to JavaScript-remove a URL anchor including the "#" sign without triggering a page refresh?

+1  A: 

Sorry to say, but the answer is no if emptying location.hash doesn't accomplish the task !-)

roenving
+8  A: 

Since you are controlling the action on the hash value, why not just use a token that means "nothing", like "#_" or "#default".

Diodeus
I think this is an idea worthy of consideration.
Jason Bunting
Yes, you can also use a blank anchor, so then the URL ends up as being http://example.com/#. This is almost perfect, but I think it can also end up looking slightly confusing to some visitors. Ideally there whouldn't even be that hash character showing...
Philipp Lenssen
Obviously. Your scripts should function with nothing in the hash.
Jenko
A: 
$(document).ready(function() {
        $(".lnk").click(function(e) {
            e.preventDefault();
            $(this).attr("href", "stripped_url_via_desired_regex");
        });
    });
Florin
Thank you Florin, could you please explain what this code does?
Philipp Lenssen
+2  A: 

So use

parent.location.hash = '' first

then do

window.location.href=window.location.href.slice(0, -1);
changing location.href in any way will reload the page.
Evgeny