Skip to main content

A JavaScript helper utility with methods for common operations.

/*!
 * JavaScript Boilerplate Helper, v1.2 Jon LaBelle
 * <https://github.com/jonlabelle>
 *
 * A modifed from original: JavaScript Boilerplate Helper
 * <https://github.com/mdarif/JavaScript-Boilerplate>
 */

(function (MODULE, $, undefined) {
  'use strict';

  /*
   * Singletons serve as a namespace provider which isolate implementation code
   * from the global namespace so as to provide a single point of access for
   * functions, this is useful for organizing code into logical sections.
   *
   * It is possible to put parentheses around this structure to instantiate it
   * immediately after it's parsed.
   *
   * This way it's always present when the script is executed and doesn't have
   * to be instantiated separately.
   */
  MODULE.helper = (function () {
    function _helper() {
      /**
       * In non-strict mode, 'this' is bound to the global scope when it isn't
       * bound to anything else.
       *
       * In strict mode it is 'undefined'. That makes it an error to use it
       * outside of a method.
       */

      /*jshint validthis: true */
      var _this = this,

        /*
         * Get an element by id
         *
         * This is the private method not meant for use as a public method.
         *
         * @param {String} el  Element Id.
         * @return {Object}    DOM element.
         */
        id = function (el) {
          return document.getElementById(el);
        },

        /*
         * Set a cookie value
         *
         * @param {String} name   Cookie name.
         * @param {String} value  Cookie value.
         * @param {Number} days   Number of days until cookie expires.
         */
        storeCookie = function (name, value, days) {
          var date = '',
            expires = '';

          if (days) {
            date = new Date();
            date.setTime(date.getTime() + (
              days * 24 * 60 * 60 * 1000));

            expires = '; expires=' + date.toGMTString();
          }

          document.cookie = name + '=' + value + expires + '; path=/';
        },

        /*
         * Get a cookie value
         *
         * @param {String} name   Cookie name.
         * @return {String|Null}  Cookie value, or null if not found.
         */
        retrieveCookie = function (name) {
          var nameEQ = name + '=',
            i,
            ca = document.cookie.split(';');
          for (i = 0; i < ca.length; i += 1) {
            var c = ca[i];
            while (c.charAt(0) === ' ') {
              c = c.substring(1, c.length);
            }
            if (c.indexOf(nameEQ) === 0) {
              return c.substring(nameEQ.length, c.length);
            }
          }
          return null;
        },

        /*
         * Delete a cookie
         *
         * @param {String} name  Cookie name.
         */
        removeCookie = function (name) {
          storeCookie(name, '', -1);
        };

      /*
       * Replace multiple values in a string
       *
       * @param {String} str   Subject string.
       * @param {Object} hash  JSON object string to be replaced.
       * @return {String}      The new string.
       */
      this.multiReplace = function (str, hash) {
        var key;
        for (key in hash) {
          if (Object.prototype.hasOwnProperty.call(hash, key)) {
            str = str.replace(new RegExp(key, 'g'), hash[key]);
          }
        }
        return str;
      };

      /*
       * Set styles for element
       *
       * @param {String} el      Element Id.
       * @param {Object} styles  Various CSS property with their values. Accepts
       * data in JSON format.
       */
      this.setCSS = function (el, styles) {
        var prop;
        for (prop in styles) {
          if (styles.hasOwnProperty(prop)) {
            _this.setStyle(el, prop, styles[prop]);
          }
        }
      };

      /*
       * Apply style to element
       *
       * @param {String} el    Element Id.
       * @param {String} prop  Style property name.
       * @param {String} val   Style property value.
       */
      this.setStyle = function (el, prop, val) {
        id(el).style[prop] = val;
      };

      /*
       * Check element for CSS class
       *
       * Determine whether the matched element is assigned the given class.
       *
       * @param {String} el  Element Id.
       * @param {String} el  CSS class name.
       * @return {Boolean}   True if element class found.
       */
      this.hasClass = function (el, name) {
        el = id(el);
        return new RegExp('(\\s|^)' + name + '(\\s|$)').test(
          el.className);
      };

      /*
       * Add CSS class to element
       *
       * @param {String} el  Element Id.
       * @param {String} el  CSS class name.
       */
      this.addClass = function (el, name) {
        if (!_this.hasClass(el, name)) {
          el = id(el);
          el.className += (el.className ? ' ' : '') + name;
        }
      };

      /*
       * Remove CSS class from element
       *
       * @param {String} el  Element Id.
       * @param {String} el  CSS class name.
       */
      this.removeClass = function (el, name) {
        if (_this.hasClass(el, name)) {
          el = id(el);
          el.className = el.className.replace(new RegExp('(\\s|^)' +
            name + '(\\s|$)'), ' ')
            .replace(/^\s+|\s+$/g, '');
        }
      };

      /*
       * Get site URI
       *
       * @return {Sting}  Returns protocol, hostname and port.
       */
      this.uri = function () {
        var port = '',
          url = '';

        if (window.location.port) {
          port = ':' + window.location.port;
        }

        url = window.location.protocol + '//' + window.location
          .hostname + port + '/';

        return url;
      };

      /*
       * Get query string value
       *
       * @param {String} key       The query string key name.
       * @param {String} default_  The default value if not found.
       * @return {String}          Query string value, or _default value
       *                           if not found.
       */
      this.queryString = function (key, default_) {
        if (default_ === null) {
          default_ = '';
        }

        key = key.replace(/\[/, "\\[").replace(/\]/, "\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)"),
          qs = regex.exec(window.location.href);

        if (qs === null) {
          return default_;
        }
        else {
          return qs[1];
        }
      };

      /*
       * Checks if string is blank, or contains all whitespace characters and
       * line feeds.
       *
       * @param {String} str  The string to check if empty.
       * @return {Boolean}    returns `true` if the string is empty, and false
       * if not.
       */
      this.empty = function (str) {
        return String(str).search(/\S/) === -1;
      };

      /*
       * Set storage item
       *
       * Store information in HTML5 localStorage if available, otherwise use
       * cookies.
       *
       * @param {String} key
       * @param {String} val
       */
      this.store = function (key, val) {
        if (typeof window.localStorage !== 'undefined') {
          localStorage.setItem(key, val);
        }
        else {
          storeCookie(key, val);
        }
      };

      /*
       * Retrieve storage item
       *
       * Get information for HTML5 localstorage if available else get
       * information from cookie.
       *
       * @param {String} key
       */
      this.retrieve = function (key) {
        var val = '';

        if (typeof window.localStorage !== 'undefined') {
          val = localStorage.getItem(key);
        }
        else {
          val = retrieveCookie(key);
        }

        return val;
      };

      /*
       * Remove storage item
       *
       * Remove information for HTML5 localStorage if available, else
       * remove information from cookie.
       *
       * @param {String} key
       */
      this.remove = function (key) {
        if (typeof window.localStorage !== 'undefined') {
          localStorage.removeItem(key);
        }
        else {
          removeCookie(key);
        }
      };

      // Returning `this` from a method is a common way to allow
      // chaining of methods together.
      this.init = function () {
        return this;
      };

      // `this` refers to MODULE.helper.init()
      return this.init();
    }

    // Creating a new object of helper rather then a funtion
    return new _helper();
  }());

  // Check to evaluate whether 'MODULE' exists in the global namespace -
  // if not, assign window.MODULE an object literal.
}(window.MODULE = window.MODULE || {}, jQuery));