Change the browser URL on click without loading the page in JavaScript

By Faruque Ahamed Mollick

Here in this post, we are going to see how to change the URL of the browser in JavaScript without loading a new page or reloading the page again on click.



Here we are going to create a simple HTML button and apply the onclick event so that whenever a user clicks the button, the URL will change but the page will not load again.

Below is the HTML code for our button:

<button onclick="change_url();">Change URL</button>

We have called the function that we want to call after clicking the button. Now below is our JavaScript function that will be called:

function change_url()
{
   window.history.pushState("object or string", "Title", "/new_url");
}

Onclick the button that we created, the above JavaScript function will call. Inside the function, we have just one line of code. This one line of code is enough to figure out our task.

Inside the function, we have used the JavaScript history object and call the pushState method. With the pushState method, we have to change the URL. We can see that we have set the last parameter to “/new_url”.

In projects many time we need to change the URL of the browser. Especially when we work on AJAX, changing URL needed there. But we should keep it in mind, we need an HTTP server to run the code.

I hope you think this post helpful.

Leave a Reply

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