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 :
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?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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With