In my last post I used URL anchors to trigger JavaScript action with a if statement like this
if (window.location.href.match(/\/\#keyword\/)) {
// do stuff
}
I've come to use this quite often which eventually leads to a considerable amount of if statements.
Which is ugly. And since I don't like ugliness, I've coded myself a small anchor handler for jQuery. Looking at the code I think I could quite easily make it compatible with the Prototype framework too, but I'll keep that for another post :D
(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)]);});});
})();
And I can add triggers like this:
$.anchorHandler
.add(/\#ch\-cheatsheet/, h.comment.showCheatsheet)
.add(/\#comment\-compose/, h.comment.showCompose)
.add(/\#comment\-\d+/, h.comment.focus);
The first argument is a regular expression or a string that is passed to the function match, the second argument is the callback function.
The method also accept arrays as argument like this:
$.anchorHandler.add([
[/\#ch\-cheatsheet/, h.comment.showCheatsheet],
[/\#comment\-compose/, h.comment.showCompose],
[/\#comment\-\d+/, h.comment.focus]]);
The callback function receive 2 arguments. The matched bit of the anchor with the anchor itself.
Most of the time I use this technique to show item that I had hidden upon page load with jQuery so that client with disabled JavaScript degrade gracefully and get the normal behaviour.
Update: Thanks to rdmey who pointed me out that I could use document.location.hash instead of a regular expression to get the anchor. I've updated the code, it makes the regex strings a lot more clean..
The backslash before the # is optional, but if I don't put it my editor screws the code highlight..
I did something similar, and a commenter pointed out that you can do document.location.hash to get the name of the anchor (I was doing it much the same way you are here). Here's what I did: http://blog.rebeccamurphey.com/2007/1...
Thanks rdmey !
Nice
permalink kevin ~ January 8, 2008 at 6:40 a.m.