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");

This is one of the methods you can use to change the url without refresh, you can also use the widow location hash to change the url, using hash location to change the url you will can detect any url changes so you can run any functions when the event is triggered. Use the following tutorial to learn more about how to detect when url is changed with hashchange.

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x