JFallz JFallz - 4 years ago 227
jQuery Question

Appending parameter to URL without refresh

I know this has been asked many times before but answers were not descriptive enough to solve my problem. I don't want to change the whole URL of page. I want to append a parameter

on button click without refresh.

document.location.search += '&item=brand';
makes the page refresh.

window.location.hash = "&item=brand";
append without refresh but with a hash
which eliminates the usage/effect of the parameter. I tried to remove the hash after appending but that didn't work.

This answer and many others suggest the use of HTML5 History API, specifically the
method, and for old browsers is to set a fragment identifier to prevent page from reloading. But how?

Assuming the URL is:

How can I append
using HTML5 pushState method or a fragment identifier so the output would be like this:
without a page refresh?

I hope someone can throw some light on how to use the HTML5 pushState to append a parameter to an existing/current URL. Or alternatively how to set a fragment identifier for the same purpose. A good tutorial, demo or piece of code with a little explanation would be great.

Demo of what I've done so far. Your answers would be greatly appreciated.

Answer Source

You need the pushState or replaceState method

window.history.pushState("object or string", "Title", "new url");


window.history.replaceState(null, null, "/another-new-url");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download