Javascript Code Replace URL No Page Reload

Javascript Code to Replace the URL Query and/or Hash of URL Without Having Reload the Web Page

Home Short:

An example of why you might wish to update a url without having to reload a web page is lets say the web page has links or tabs that display a related div for example and you want the clicking of the different tabs to be stored in the browsers history so when the user clicks the back or forward button, instead of navigating to the previous full url, the browser instead navigates to the previous query part of the url that is stored in the history stack. This results in a more accurate/better user experience.

To see in action the javascript code that updates the browser query url in the address bar, click on the different 'tabs' below show greenshow redshow purple and notice how the query string in the browsers address bar changes without the page having to reload.

Explanation:

  1. history.pushState(...)
    • This method allows you to modify the browser's history without causing a page reload.
    • It adds a new entry to the browser's session history stack.
  1. { tab: tabName } (First Argument)
    • This is the state object. It allows you to store custom data (in this case, { tab: tabName }) associated with the new history entry.
    • Later, when the user navigates back or forward, this data is passed to the window.onpopstate event.
    • In this example:
      • tab is the property name.
      • tabName is the value, which represents the name of the currently active tab (e.g., "green", "red", "purple").
  1. "" (Second Argument)
    • This is the title of the new history entry.
    • Although it's included for completeness, modern browsers ignore this argument. You can leave it as an empty string ("") or provide a descriptive title for future compatibility.
  1. "?section=" + tabName (Third Argument)
    • This is the URL to display in the browser's address bar.
    • It updates the visible URL to match the new state (e.g., ?section=green or ?section=red) without reloading the page.
    • The actual URL shown in the browser is constructed dynamically:
      • "section=" is a query parameter indicating the current section or tab.
      • tabName is appended to the parameter to reflect the active tab (e.g., green, red, or purple).

The full javascript code for this page:

S
H
A
R
E