hashbang.js monitors the URL fragment (hashtag) for changes and invokes callbacks when they occur. You can specify a fragment as a string or a regular expression, and callbacks that should be fired when the fragment appears and disappears from the URL.
Examples:
As a complete object, with both plain string and regular expression matches, and 'load' and 'unload' callbacks:
hashbang({
'#home': {
load: function() {
// '#home' fragment appeared in the url
},
unload: function() {
// browser navigated away from '#home';
// 'newFragment' will contain the current fragment
}
},
'/#(.*)/': {
load: function() {
// A fragment that matched the /#(.*)/ regular expression appeared in the url
},
unload: function() {
// browser navigated away from the previously matched fragment;
// 'newFragment' will contain the current fragment
}
}
});
If you don't need any unload
functions, you can reduce the example down to this:
hashbang({
'#home': function() {
// '#home' fragment appeared in the url
},
'/#(.*)/': function(fragment, matches) {
// A fragment that matched the /#(.*)/ regular expression appeared in the url
// 'fragment' will contain the entire fragment
// 'matches' is the result of JavaScript's 'match' function (an array of match groups)
}
});
If you only need to match one fragment, you can pass the fragment matcher and callbacks as individual parameters instead of an object:
hashbang(
'#home',
// 'load' callback
function() {
// '#home' fragment appeared in the url
},
// 'unload' callback (optional)
function(newFragment) {
// browser navigated away from '#home';
// 'newFragment' will contain the current fragment
}
);
-
hashbang.handle(defaultFragment)
Hashbang.js does not automatically handle the fragment in the url when the page loads. Call this method to handle the current fragment.
defaultFragment
- If no fragment is present in the current url, hashbang.js will treat it as if this fragment was present instead.// This will process the current location's fragment, or '#home' if no fragment is in the current url. hashbang.handle('#home');
-
hashbang.go(fragment, enableHistory)
Use this method to send the user to a specific url fragment.
fragment
- the fragment to navigate to (including the # symbol)enableHistory
-true
to add the new url to the user's browser history,false
to "silently" navigate.