Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a window's URL hash with another response?

I am trying to change a hashed URL (document.location.hash) with the replace method, but it doesn't work.

$(function(){  var anchor = document.location.hash;  //this returns me a string value like '#categories'    $('span').click(function(){       $(window).attr('url').replace(anchor,'#food');      //try to change current url.hash '#categories'      //with another string, I stucked here.   });  }); 

I dont want to change/refresh page, I just want to replace URL without any responses.

Note: I don't want to solve this with a href="#food" solution.

like image 904
Barlas Apaydin Avatar asked Jul 21 '12 00:07

Barlas Apaydin


People also ask

How do I change the URL of a hash?

Change hash of the current url URL is the current url var url_ob = new URL(document. URL); url_ob. hash = '#345'; // new url var new_url = url_ob. href; // change the current url document.

What is the hash of a URL?

In a URL, a hash mark, number sign, or pound sign ( # ) points a browser to a specific spot in a page or website. It is used to separate the URI of an object from a fragment identifier.


2 Answers

Either use location or window.location instead of document.location as the latter is a non-standard.

window.location.hash = '#food'; 

This will replace the URL's hash with the value you set for it.

Reference

like image 183
Fabrício Matté Avatar answered Oct 10 '22 23:10

Fabrício Matté


You may prefer the answer of this question.

The difference being that with history.replaceState() you don't scroll to the anchor, only replace it in the navigation bar. It's supported by all major browsers, source.

history.replaceState(undefined, undefined, "#hash_value") 
like image 38
arc Avatar answered Oct 11 '22 00:10

arc