Light­weight Util­i­ty Object

Publisher: TJ Fogarty

Modified: 2018-03-13

I’m work­ing on a lit­tle project, and it’s fair­ly light­weight. I end­ed up cre­at­ing a JavaScript object with a few func­tions to help with the most com­mon tasks, e.g. add class, tog­gle class, select element…

It’s just a col­lec­tion assem­bled from You Might Not Need jQuery.

Exam­ple usage:

U.ready(function() {
  console.log('Ready to go!');
});

I’d usu­al­ly have this export­ed as a sep­a­rate mod­ule using Browser­i­fy or ES2015.

/**
 * Utilities 
 * see http://youmightnotneedjquery.com/
 * @type {Object}
 */
var U = {
  /**
   * Call a function when DOM is ready
   * @param  {Function} fn Function to call when DOM is ready
   */
  ready: function(fn) {
    if (document.readyState !== 'loading') {
      fn();
    } else {
      document.addEventListener('DOMContentLoaded', fn);
    }
  },

  /**
   * Select a DOM element
   * @param  {String} selector 
   * @return {DOM Element}
   */
  qsa: function(selector) {
    return document.querySelectorAll(selector);
  },

  /**
   * Add class
   * @param {String} el        DOM Selector
   * @param {String} className Class to add to el
   */
  addClass: function(el, className) {
    if (el.classList) {
      el.classList.add(className);
    } else {
      el.className += ' ' + className;
    }
  },

  /**
   * Check if an element has a given class
   * @param  {String}  el        Selector string to check
   * @param  {String}  className Class to check against
   * @return {Boolean}
   */
  hasClass: function(el, className) {
    if (el.classList) {
      el.classList.contains(className);
    } else {
      new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
    }
  },

  /**
   * Remove class
   * @param {String}  el        DOM Selector
   * @param {String}  className Class to remove from el
   */
  removeClass: function(el, className) {
    if (el.classList) {
      el.classList.remove(className);
    } else {
      el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }
  },

  /**
   * Toggle class
   * @param {String}  el        DOM Selector
   * @param {String}  className Class to toggle on el
   */
  toggleClass: function(el, className) {
    if (el.classList) {
      el.classList.toggle(className);
    } else {
      var classes = el.className.split(' ');
      var existingIndex = classes.indexOf(className);

      if (existingIndex >= 0) {
        classes.splice(existingIndex, 1);
      } else {
        classes.push(className);
      }

      el.className = classes.join(' ');
    }
  }
};

View the Gist