Change URL without refresh jquery – history.pushState

Change URL without refresh jquery – history.pushState

Even if you make a website with ajax or you have to add a string in the url when you activate a tab by javascript, you need to do this manually. 

One method would be hashtag, to add a hastag to url you have to use the following line of javascript:

window.location.hash = 'tutorial';

If you want to see how this line of code works, you can open up the console, press the second click and Inspect, then find the console tab and copy/paste the above line of code and hit enter. Then you should see in the url "#tutorial" string.

 

Anyway this method works good  but that "#" looks bad in the url, especially when you have to use more then one hashtag.  Advent of html5 we have some advantages and we can use few methods to add new "pages" in user history.

The history object gives us the opportunity to move back and forth through the user's history. 

If you want to load a specific page from history you can use the following code: history.go(1) or history.go(-1) the pages are finded by your current position in the history object.

To add new string to URL we will use the folowing bunch of code:

history.pushState(null, null, "new_tutorial_page");

 

History.pushState will add a new string to URL but it will appear in this way: "/new_tutorial_page". 

Let's assume you have to following url:  /page/new_tutorial/tutorial if you want to change the url to: "/page/my_tutorial" you have to use the following code:

history.replaceState(null, null, "/page/my_tutorial");

 

Leave a Reply

Your email address will not be published. Required fields are marked *