Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change URL in browser address bar without reload existing page [duplicate]

Possible Duplicate:
Modify the URL without reloading the page

I'm looking for a way to make my internal links functional using my current javascript animations, without causing the page to reload when you click on them - but I would like the URL to update in the browser.

Many websites do this, here is a good example: http://grooveshark.com/#!/search?q=adf

How do they get the URL to update without the page reloading?


More details:

Currently a link on my page looks like <a href="#aboutus">About Us</a>, this takes you to <div id="aboutus"></div> via javascript.

The javascript looks something like:

$("#navigation a").click(function(e){   animate(..scroll to section..);   e.preventDefault(); // <========== }); 

I believe the "e.preventDefault()" is what is causing the URL to not be updated, but how do I prevent the browser from reloading the page when the URL is changed?

How do other websites do it? What is this method called (so I can further research it)?

thanks.

like image 917
Radley Sustaire Avatar asked Jun 08 '12 18:06

Radley Sustaire


People also ask

How do I change URL without loading page?

In modern browsers and HTML5, there is a method called pushState on window history . That will change the URL and push it to the history without loading the page. You can use it like this, it will take 3 parameters, 1) state object 2) title and a URL): window.

Which method is used to change the address in address bar of the browser?

HTML5 History API allows browsers to change the URL in browser address bar without reloading or refreshing the page using pushState function. The pushState method works similar to window.


2 Answers

Here is a similar question.

Here is an example:

function processAjaxData(response, urlPath){     document.getElementById("content").innerHTML = response.html;     document.title = response.pageTitle;     window.history.pushState(         {             "html":response.html,             "pageTitle":response.pageTitle         },         "",         urlPath    ); } 
like image 59
Maziar Aboualizadehbehbahani Avatar answered Oct 07 '22 03:10

Maziar Aboualizadehbehbahani


It looks to me like the whole thing is done with AJAX. The #! in the URL is causing the browser to interpret the remainder of the URL as an anchor -- anchors don't cause page reloads (in fact, the server will never see what anchor the browser is on in the course of a normal HTTP request). When the URL changes, Javascript takes over, inspects the querystring, and loads whatever is appropriate from the server using web services.

I haven't looked at it too much in depth, but that is what it looks like to me.

like image 35
Katie Kilian Avatar answered Oct 07 '22 02:10

Katie Kilian