Wednesday, October 13, 2010

How to change URL without refreshing?

You can change the URL without refreshing  with  location.hash  .

For ex: facebook and twitter use this method.

http://twitter.com/#!/username

Browsers use the # symbol as page anchors and you create your own prefix to catch the URL like #!
You can  listen to URL with  window.onhaschange  to send a XHTTP request when it changes.

Example:
<script type="text/javascript"> 
window.onhashchange = function() {
    var link = location.hash.replace('#!','');
// add  your XHTTP request code here
    alert('URL changed. Your link is "'+ link +'"');
}
</script>
<a href="#!/en/home/">change url</a>

If you wish to check browsers' onhaschange capability, you can use the code below:


<script type="text/javascript">
if ("onhashchange" in window) { alert('location hash is enable!'); } 
</script> 

No comments:

Post a Comment