Skip to content

Instantly share code, notes, and snippets.

@ajaegers
Created December 9, 2016 15:16
Show Gist options
  • Save ajaegers/72c17077ab5be1587db1c078d8726a2c to your computer and use it in GitHub Desktop.
Save ajaegers/72c17077ab5be1587db1c078d8726a2c to your computer and use it in GitHub Desktop.
Javascript Vanilla functions
function hasClass(el, className) {
return el.classList ? el.classList.contains(className) : new RegExp('\\b' + className + '\\b').test(el.className);
}
function addClass(el, className) {
if (el.classList) el.classList.add(className);
else if (!hasClass(el, className)) el.className += ' ' + className;
}
function removeClass(el, className) {
if (el.classList) el.classList.remove(className);
else el.className = el.className.replace(new RegExp('\\b' + className + '\\b', 'g'), '');
}
function toggleClass(el, className){
if(hasClass(el, className)) removeClass(el, className);
else addClass(el, className);
}
function addEvent(el, type, handler) {
if (el.attachEvent) el.attachEvent('on' + type, handler); else el.addEventListener(type, handler, false);
}
function removeEvent(el, type, handler) {
if (el.detachEvent) el.detachEvent('on' + type, handler); else el.removeEventListener(type, handler, false);
}
function throttle(fn, threshhold, scope) {
threshhold || (threshhold = 250);
var last,
deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment