Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change URL without reloading? [duplicate]

OK, this what I'm trying to do (I think Google mostly does this as well) :

Scenario A :

In page /Main_Page let's say there are 3 sections. When user clicks on section A "link", section A's content is loaded through AJAX and embedded into the page.

Scenario B :

When /Main_Page/Section_A is loaded, we practically go to the very same page (as in scenario A) - /Main_Page and load Section A via AJAX - as before.


The problem :

We've got 2 identical resulting pages, but the URL is different (in the first case it'll be just /Main_Page, while in the second it will be /Main_Page/Section_A).

What I want to do :

  • In Scenario A, after loading Section A via AJAX, how should I do it so that the appearing URL (in the browser address bar) is /Main_Page/Section_A (or anything else for that matter), without any sort of redirecting, page reloading, etc?
like image 329
Dr.Kameleon Avatar asked Aug 13 '12 10:08

Dr.Kameleon


People also ask

How do I change URL without reloading page?

There is no way to modify the URL in the browser without reloading the page. The URL represents what the last loaded page was. If you change it ( document. location ) then it will reload the page.

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

Your problem can be solved by implementing the History API, especially by using the pushState() method. I recommend reading about it in MDN. There's also an all-in-one solution called History.js, it will help you implement it x-browser easily (It will fallback to URL hashes # if the browser doesn't support it).

Here's an example:

history.pushState('', 'New Page Title', newHREF); 

Not excited enough? Here's a demo that will encourage you to implement it.

like image 96
Adi Avatar answered Oct 02 '22 21:10

Adi


I just found a tutorial and it worked for me,

$('a').click(function(){ var value = $(this).attr('id'); window.location.hash = value; // it appends id to url without refresh });   $(window).bind('hashchange' function() {     var newhash = window.location.hash.substring(1) // it gets id of clicked element     // use load function of jquery to do the necessary... }); 

i got the above code from http://css-tricks.com/video-screencasts/85-best-practices-dynamic-content/

like image 43
Pavan Mehta Avatar answered Oct 02 '22 22:10

Pavan Mehta