Skip to content

Instantly share code, notes, and snippets.

@tjFogarty
Created July 26, 2015 20:00
Show Gist options
  • Save tjFogarty/04a797998fc1df10e5fe to your computer and use it in GitHub Desktop.
Save tjFogarty/04a797998fc1df10e5fe to your computer and use it in GitHub Desktop.
Little utility object
/**
* 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(' ');
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment