jquery: change the URL address without redirecting?

laukok picture laukok · Jun 25, 2011 · Viewed 181.3k times · Source

Possible Duplicate:
Modify Address Bar URL in AJAX App to Match Current State

How can I change the URL address without redirecting the page?

For instance, when I click on this link below:

<a href="http://mysite.com/projects/article-1" class="get-article">link</a>

I will grab the URL from the link:

var path = object.attr('href');

If I do this below, the page will be redirected:

window.location = path;

I want to do something like this site, when you click on the image, the ajax call will fetch the requested page and the URL address on the window will be changed too, so that it has a path for what you click.

Answer

david picture david · Jun 25, 2011

NOTE: history.pushState() is now supported - see other answers.

You cannot change the whole url without redirecting, what you can do instead is change the hash.

The hash is the part of the url that goes after the # symbol. That was initially intended to direct you (locally) to sections of your HTML document, but you can read and modify it through javascript to use it somewhat like a global variable.


If applied well, this technique is useful in two ways:

  1. the browser history will remember each different step you took (since the url+hash changed)
  2. you can have an address which links not only to a particular html document, but also gives your javascript a clue about what to do. That means you end up pointing to a state inside your web app.

To change the hash you can do:

document.location.hash = "show_picture";

To watch for hash changes you have to do something like:

window.onhashchange = function(){
    var what_to_do = document.location.hash;    
    if (what_to_do=="#show_picture")
        show_picture();
}

Of course the hash is just a string, so you can do pretty much what you like with it. For example you can put a whole object there if you use JSON to stringify it.

There are very good JQuery libraries to do advanced things with that.