Newly Paranoid Maintainers

    hash-handler

    2.0.1 • Public • Published

    hash-handler

    npm Travis David

    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:

    // ES6
    import Hash from 'hash-handler';
     
    // CommonJS
    var 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 values
    hash.set({
      color: 'blue'
    });
     
    // get hash query string object
    console.log(hash.get()); // => { age: 5, color: 'blue' }
     
    // replace whole hash
    hash.replace({
      age: 7
    });
     
    console.log(hash.get()); // => { age: 7 }
     
    const handler = () => {
      // do stuff
    };
     
    // listen for hash changes
    hash.registerListener(handler);
     
    // stop listening
    hash.removeListener(handler);
     
    // remove all handlers and event listener
    hash.destroy();

    API

    Hash()

    Initializes hash-handler instance.

    const hash = Hash();

    Hash.get()

    Returns parsed query string hash.

    // http://www.example.com/#name=max
    console.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();

    License

    MIT © Lars Graubner

    Install

    npm i hash-handler

    DownloadsWeekly Downloads

    15

    Version

    2.0.1

    License

    MIT

    Last publish

    Collaborators

    • graubnla