How To Change Page URL And Detect Event Without Refresh

In the last tutorial about changing the page URL we used history pushstate, and in this part of tutorial seriers I will show you another method to change the page url without refresh but this time we will use window location hash. This method is good enough, the bad part at this method is the URL because it will have # in it, but with few lines of javascript you can get rid of it. Using window location hash you can use all the browser features like back or forward buttons because the browser will save the hash location in browser history. As the title said we can detect any url change if we use the location hash javascript feature. You can use this method when you have a site with ajax because you can send any parameters you need in the browser url and then get them in javascript or php. 

To add a new hash in the url you have to run the following code:

window.location.hash = 'aboutus-page';

With the above line of code we will add #aboutus-page to the URL and the page won't refresh. From here we can do everything we need with this parameter. If we want to remove it we can use the following line of code:

function removeHash () { 
    history.pushState("", document.title, window.location.pathname
                                                       + window.location.search);
}

If you don't want to add hash to your URL you can choose other methods like history push state, which is html5 feature and it works almost like window location hash, but in my opinion window location hash is more stable and you can detect any url change with it. You can learn more about how to change url with history push state here.

Using the following function you will be able to detect any url change (or any hash change). You can make this function once, and every time when you will use window.location.hash the function will be triggered.

jQuery(window).on('hashchange', function(){
    var hash = window.location.hash;
    console.log(hash);
});

With the above function you will be noticed every time a hash is changed so you can do any functions at hash change. This is how you can change the url without refresh using location hash.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x