Created
December 9, 2016 15:16
-
-
Save ajaegers/72c17077ab5be1587db1c078d8726a2c to your computer and use it in GitHub Desktop.
Javascript Vanilla functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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