views:

48

answers:

6

I am trying to use jQuery to respond to changes in the url after the #. I've done some searching, but I don't think I'm using the right search terms.

To be clear, I want to be able to provide external links to a page like so:

<a href="example.com/foo/#home">home</a>

and to include internal links to change the content on the page dynamically:

<a href="#site-index">site index</a>

Gmail does this. For example, I can link you straight to your sent box: https://mail.google.com/mail/u/0/#sent

Thanks.

A: 

I believe that the term you want is fragment.

Mike
In JS: `document.location.hash`
jball
+1  A: 

Look into the HTML 5 hashchange event and the jQuery Back Button & Query plugin to provide that for older browsers.

bdukes
A: 

I think the jQuery History plugin does exactly what you want to do.

stevelove
+2  A: 

Is this what you're looking for:

http://haineault.com/blog/37/

(function(){
  anchor = document.location.hash, handlers = [];

  jQuery.extend({
    anchorHandler: {
      add: function(regexp, callback) {
        if (typeof(regexp) == 'object') {
          jQuery.map(regexp, function(arg){
            args = {r: arg[0], cb: arg[1]};});}
        else  args = {r: regexp, cb: callback};
        handlers.push(args);
        return jQuery.anchorHandler;
      }
    }
  })(document).ready(function(){
    jQuery.map(handlers, function(handler){
      match = anchor.match(handler.r) && anchor.match(handler.r)[0] || false;
      if (match) handler.cb.apply(this, [match, (anchor || false)]);});});
})();

Add triggers like this:

$.anchorHandler
  .add(/\#ch\-cheatsheet/,    h.comment.showCheatsheet)
  .add(/\#comment\-compose/,  h.comment.showCompose)
  .add(/\#comment\-\d+/,      h.comment.focus);
Edward M Smith
A: 

Here is a super simple example:

if (location.hash != "")
{
    Location.hash.replace(
        new RegExp( "([^#?=&]+)(=([^&]*))?", "g" ),
            function( $0, $1, $2, $3 ){
                eval($1 + "='" + $3 + "'");
             });
}

This a method i've used in the past (in a kind of hacky way) to eval all the variable, this will turn the following:

#id=1&blah=cheese

into javascript variables of id and blah with the correct values, quick and simple :)

Paul Creasey
I always laugh a little bit when a regexp is referred to as "super simple."
Jonathan Swinney
@Jonathan, I always laugh when people jump on anti-regex bandwagon for no reason, regex is a language like any other, if you speak the language that is a simple regex, if not then you won't understand. It's no more hard to understand than a simple c program.
Paul Creasey
A: 

JQuery doesn't have an event to respond to hash changes in the URI. After the document is ready, you examine the hash and alter the page appropriately. You can intercept your hash anchors' click events and respond appropriately thereafter. Alternatively, you can create a synthetic "hash changed" event by inspecting window.location.hash on a timer.

Sephrial