hash-handler
Handle location hash query strings with ease.
Aims to make working with location hash and query strings easier. Get and set query strings as simple objects and listen for hash changes. Query string arguments get sorted to guarantee consistent URL's.
Table of contents
Install
This module is available on npm.
$ npm install hash-handler
If you are using some kind of bundler (webpack, rollup...) you can import it like this:
// ES6import Hash from 'hash-handler'; // CommonJSvar Hash = require('hash-handler');
The UMD build is also available on unpkg:
<script src="https://unpkg.com/hash-handler/dist/hashHandler.js"></script>
Usage
import Hash from 'hash-handler'; const hash = Hash(); // set hash value(s)hash.set({ age: 5}); // set more hash valueshash.set({ color: 'blue'}); // get hash query string objectconsole.log(hash.get()); // => { age: 5, color: 'blue' } // replace whole hashhash.replace({ age: 7}); console.log(hash.get()); // => { age: 7 } const handler = () => { // do stuff}; // listen for hash changeshash.registerListener(handler); // stop listeninghash.removeListener(handler); // remove all handlers and event listenerhash.destroy();
API
Hash()
Initializes hash-handler instance.
const hash = Hash();
Hash.get()
Returns parsed query string hash.
// http://www.example.com/#name=maxconsole.log(hash.get()); // => { name: 'max' }
Hash.set(newHash)
Sets the hash query string. Extends existing key value pairs.
hash.set({ name: 'max'}); // http://example.com/#name=max
Hash.replace(newHash)
Replace existing hash query string.
hash.replace({ animal: 'shark'});
Hash.clear()
Removes the hash fragment. The hash itself will remain.
hash.clear();
Hash.registerListener(handler)
Registers a handler to be executed on hash change.
hash.registerListener((hash) => { // called everytime hash changes console.log(hash); // new hash});
Hash.removeListener(handler)
Removes registered listener function.
hash.removeListener(handler);
Hash.destroy()
Remove all handlers and hashchange event listener.
hash.destroy();