How to monitor the changes in the url (Fragment identifier - the anchor portion of a URL )

6.2k views Asked by At

I'm making a website that tend to handle all the request in one page (Ajax). so i thought that I could trap every user's click on a link and check IF it's on my website i do something on JavaScript like an ajax request for example, ELSE it would open the link like usual!

doing a watch on window.location did not work! and moreover I don't know if there is anyway to get the url part that is after the # sign. Note: both GMail, and Facebook does that I guess!, they use something like this:
http://mail.google.com/mail/#inbox
http://www.facebook.com/home.php#/inbox/?ref=mb

Kindly Consider: that I love to use jQuery in my projects, so any solution using it is preferred.

Any ideas?

5

There are 5 answers

1
o.k.w On BEST ANSWER

Here is another good read: Restoring Conventional Browser Navigation to AJAX Applications

Excerpt from the article:

Many developers have adopted AJAX as a way to develop rich web applications that are almost as interactive and responsive as desktop applications. AJAX works by dividing the web UI into different segments. A user can perform an operation on one segment and then start working on other segments without waiting for the first operation to finish.

But AJAX has a major disadvantage; it breaks standard browser behavior, such as Back, Forward, and bookmarking support. Rather than forcing users to adapt to AJAX's shortcomings, developers should make their AJAX applications comply with the traditional web interaction style,.......

0
Pekka On

Simple:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}

Link: How can you check for a #hash in a URL using JavaScript?

0
Tamas Czinege On

The fragment part of the URL is used to enable navigation history (back and forward buttons) on AJAX-enabled websites. If you want to "trap" clicks on links, since you're using jQuery anyway, you could just do that:

$('a').click(function()
{
   var item = $(this);
   var url = item.attr('href');
   // your logic here
});

If you use fragments (window.location.hash) in constellation with AJAX, note that IE6 submits the fragment part of the url in AJAX requests which can lead to very hard-to-debug bugs, so be aware of that.

4
Justin On

See @Pekka 's link to How can you check for a #hash in a URL using JavaScript? to look at the hash. Just put that function in the callback to window.setInterval()

2
Eli Grey On

There's a hashchange event dispatched on the window for most recent browsers.