Skip to content

Instantly share code, notes, and snippets.

@tjFogarty tjFogarty/utils.js
Created Jul 26, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.