Last active
March 16, 2018 18:07
-
-
Save nydame/cd383a4b371ab559a118 to your computer and use it in GitHub Desktop.
A few vanilla JavaScript utility 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
// 1. Add and remove classes jQuery-style | |
/** | |
* Determines if a given thing is in a given array. | |
* @param {any} x An object or primitive whose presence in a is being queried | |
* @param {Array} a Array being queried | |
* @return {number} -1 if x could not be found in a; otherwise index where it was first found, so 0 would be minimum value | |
*/ | |
function isThingInArray(x, a) { | |
if ( Array.isArray(a) ) { | |
for (var i = a.length - 1; i >= 0; i--) { | |
if ( x === a[i] ) { return a.indexOf(x); } | |
}; | |
} | |
// either a is not an array or x is not in a | |
return -1; | |
} | |
/** | |
* Adds class to DOM element if it's not already a class of that element. | |
* @param {String} s Class name to add | |
* @param {DOM Node} el Element that will take new class | |
*/ | |
function addClassToEl(s, el) { | |
var elClassList = el.className.split(" "); | |
if ( isThingInArray( s, elClassList ) < 0 ) { | |
elClassList.push(s); | |
el.className = elClassList.join(" "); | |
} | |
} | |
/** | |
* Removes class from DOM element, even if it's present more than once. | |
* @param {String} s Class name to remove | |
* @param {DOM Node} el Element that will lose class name | |
*/ | |
function removeClassFromEl(s, el) { | |
var elClassList = el.className.split(" "), | |
i; | |
i = isThingInArray( s, elClassList ); | |
if ( i >= 0 ) { | |
//use while in case s is present multiple times | |
while ( i >= 0) { | |
// remove ith item in classList | |
elClassList.splice(i, 1); | |
// update counter within loop | |
i = isThingInArray( s, elClassList ); | |
} | |
el.className = elClassList.join(" "); | |
} | |
} | |
// 2. Wrap code in "ready()" | |
document.addEventListener('readystatechange', () => { | |
if (document.readyState === 'complete') { | |
// put code here | |
} | |
}); | |
// 3. Is this a touch device? | |
/** | |
* Return true if device is a touch device | |
*/ | |
function isTouchDevice() { | |
return ('ontouchstart' in document.doucumentElement); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment