Skip to content

Instantly share code, notes, and snippets.

@hasibomi
Last active July 20, 2023 22:47
Show Gist options
  • Save hasibomi/b23ea8e9e1ad7c5d88349ddf863a7a6f to your computer and use it in GitHub Desktop.
Save hasibomi/b23ea8e9e1ad7c5d88349ddf863a7a6f to your computer and use it in GitHub Desktop.
Change URL in Browser Address Bar without reloading using JavaScript and jQuery
/* The solution found here: http://www.aspsnippets.com/Articles/Change-URL-in-Browser-Address-Bar-without-reloading-using-JavaScript-and-jQuery.aspx */
/** HTML5 History pushState method
* The pushState method works similar to window.location but it does not refresh or reload the page and it will modify the URL even if the page does not exists. The pushState method actually inserts an entry into the history of the browsers which allows us to go back and forth using the browser’s forward and back buttons.
* The pushState method accepts the following three parameters.
* 1. State object: - The state object is a JavaScript object which can contain any details about the page and must be serializable.
* 2. Title: - The title of the page.
* 3. URL – The URL of the page.
*/
/** Using JavaScript */
function ChangeUrl(title, url) {
if (typeof (history.pushState) != "undefined") {
var obj = { Title: title, Url: url };
history.pushState(obj, obj.Title, obj.Url);
} else {
alert("Browser does not support HTML5.");
}
}
/** Using jQuery */
$(function () {
/** ChangeUrl() referes to the function above. */
$("#button1").click(function () {
ChangeUrl('Page1', 'Page1.htm');
});
$("#button2").click(function () {
ChangeUrl('Page2', 'Page2.htm');
});
$("#button3").click(function () {
ChangeUrl('Page3', 'Page3.htm');
});
});
@mrahroy
Copy link

mrahroy commented Aug 31, 2018

nice bro. but i want to implement it on pageload instead of buttons but it didn't work. Moreover, i tend to change the who url instead of merely a part of it. please help.

@krystian-broniszewski
Copy link

great, but how include automaticly on page load?

@hasibomi
Copy link
Author

hasibomi commented Jan 10, 2021

but how include automaticly on page

Better to use a Framework in that case.

@hasibomi
Copy link
Author

nice bro. but i want to implement it on pageload instead of buttons but it didn't work. Moreover, i tend to change the who url instead of merely a part of it. please help.

Please use a framework/library for your case. I don't think you can change the whole url with HTML 5 history api.

@krystian-broniszewski
Copy link

krystian-broniszewski commented Jan 10, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment