├── .DS_Store ├── DOMready.js ├── README.md ├── add-array-values.js ├── add-remove-class.js ├── addEvent-loop.js ├── addEventListenerFallback.js ├── addEventListenerPolyfill.js ├── animate.js ├── animationEventListener.js ├── autoHideSticky.js ├── bind.js ├── bindPolyfill.js ├── capitalizeEachWord.js ├── checkActiveCategory.js ├── checkMedia.js ├── checkUrlHash.js ├── checkVisibility.js ├── classList-polyfill.js ├── classList.js ├── closestParent.js ├── cross-bowser-class-handlers.js ├── cssSupports.js ├── cutsMustard.js ├── debounce.js ├── delegate-event.js ├── event-polyfill.js ├── eventBinding.js ├── extend.js ├── fluidVids.js ├── forEach.js ├── forEachLoop.js ├── get-anchor.js ├── get-widths-from-list.js ├── getAbsoluteUrl.js ├── getClosest.js ├── getClosestAlt.js ├── getComputedStyle.js ├── getCurrentScroll.js ├── getDocumentHeight.js ├── getElemDistance.js ├── getElemInfo.js ├── getHeight.js ├── getIndex.js ├── getJSONP.js ├── getMaxWidth.js ├── getNextSibling.js ├── getNextUntil.js ├── getPageName.js ├── getParents.js ├── getParentsUntil.js ├── getPreviousSibling.js ├── getPreviousUntil.js ├── getQueryString.js ├── getSiblings.js ├── getSupportedPropertyName.js ├── getSvgSprite.js ├── getURL.js ├── getViewportSize.js ├── handleEvent.js ├── hasClass.js ├── iconsFallback.js ├── iife.js ├── insertRule.js ├── isInViewport.js ├── isValidEmail.js ├── isVisible.js ├── lazyLoadImages.js ├── loadCSS.js ├── loadSVG.js ├── loadScript.js ├── loops.js ├── manipulateDom.js ├── matchMediaListener.js ├── matchesSelector.js ├── mediaQueryTest.js ├── navigation.js ├── nextUntil.js ├── nodelist.forEach.js ├── objectPropLoop.js ├── on.js ├── onAnimationEnd.js ├── once.js ├── onetime.js ├── optimizedScrollEvent.js ├── parallaxOpacity.js ├── parallaxPosition.js ├── pointerEvents.js ├── poll.js ├── prefixedEvent.js ├── prevUntil.js ├── ready.js ├── remove-array-duplicates.js ├── removeClass.js ├── removeElem.js ├── removeHyphens.js ├── removeQuotes.js ├── replaceNoJS.js ├── requestAnimThrottle.js ├── resetActiveClass.js ├── revealing-module-pattern-constructor.js ├── revealing-module-pattern-options.js ├── revealing-module-pattern.js ├── reverseHeader.js ├── scrollToTop.js ├── show-nav-desc.js ├── skip-link-focus-fix.js ├── splitAnchor.js ├── stickyElement.js ├── stickyFooter.js ├── stringToHTML.js ├── supports.js ├── supportsSvg.js ├── svg.js ├── throttle.js ├── titleCase.js ├── toggleElem.js ├── toggleNav.js ├── transforms.js ├── traverse.js ├── truncate.js ├── uppercaseFirstLetter.js └── whichTransitionEvent.js /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonyablonski/javascript-toolbox/52047665175a5d047622debeda38cdfa61596856/.DS_Store -------------------------------------------------------------------------------- /DOMready.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Document Ready 3 | * Same as jQuery .ready method 4 | * ! Putting JS at the bottom of the page does the same thing 5 | */ 6 | document.addEventListener("DOMContentLoaded", function() { 7 | // Code 8 | }, false); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | javascript-toolbox 2 | ================== 3 | 4 | A collection of useful javascript snippets. 5 | -------------------------------------------------------------------------------- /add-array-values.js: -------------------------------------------------------------------------------- 1 | let sum = item.reduce((accumulator, value) => { 2 | return accumulator + value; 3 | }, 0); -------------------------------------------------------------------------------- /add-remove-class.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Various ways to add/remove classes 3 | */ 4 | 5 | // Select an element 6 | var element = document.querySelector(".some-class"); 7 | 8 | // Give class "foo" to the element 9 | element.className = "foo"; 10 | 11 | // Adding a class without replacing the current classes 12 | element.className += " foo"; 13 | 14 | // Removing "no-js" class from html-element and replacing it with "js" 15 | document.documentElement.className = "js"; -------------------------------------------------------------------------------- /addEvent-loop.js: -------------------------------------------------------------------------------- 1 | /** 2 | * addEventListener to collection 3 | */ 4 | 5 | // Select all links 6 | var links = document.querySelectorAll("a"); 7 | 8 | // For each link element 9 | [].forEach.call(links, function(el) { 10 | 11 | // Add event listener 12 | el.addEventListener("click", function(event) { 13 | event.preventDefault(); 14 | alert("You clicked"); 15 | }, false); 16 | 17 | }); -------------------------------------------------------------------------------- /addEventListenerFallback.js: -------------------------------------------------------------------------------- 1 | if (document.addEventListener) { 2 | el.addEventListener('click', modifyText, false); 3 | } else if (document.attachEvent) { 4 | el.attachEvent('onclick', modifyText); 5 | } -------------------------------------------------------------------------------- /addEventListenerPolyfill.js: -------------------------------------------------------------------------------- 1 | // Polyfill event.preventDefault & event.addEventListener 2 | if (!window.addEventListener) { 3 | (function() { 4 | if (!Event.prototype.preventDefault) { 5 | Event.prototype.preventDefault=function() { 6 | this.returnValue=false; 7 | }; 8 | } 9 | if (!Event.prototype.stopPropagation) { 10 | Event.prototype.stopPropagation=function() { 11 | this.cancelBubble=true; 12 | }; 13 | } 14 | if (!Element.prototype.addEventListener) { 15 | var eventListeners=[]; 16 | var addEventListener=function(type,listener /*, useCapture (will be ignored) */) { 17 | var self=this; 18 | var wrapper=function(e) { 19 | e.target=e.srcElement; 20 | e.currentTarget=self; 21 | if (listener.handleEvent) { 22 | listener.handleEvent(e); 23 | } else { 24 | listener.call(self,e); 25 | } 26 | }; 27 | if (type=="DOMContentLoaded") { 28 | var wrapper2=function(e) { 29 | if (document.readyState=="complete") { 30 | wrapper(e); 31 | } 32 | }; 33 | document.attachEvent("onreadystatechange",wrapper2); 34 | eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper2}); 35 | if (document.readyState=="complete") { 36 | var e=new Event(); 37 | e.srcElement=window; 38 | wrapper2(e); 39 | } 40 | } else { 41 | this.attachEvent("on"+type,wrapper); 42 | eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper}); 43 | } 44 | }; 45 | var removeEventListener=function(type,listener /*, useCapture (will be ignored) */) { 46 | var counter=0; 47 | while (counter { 5 | 6 | // If there's no element or animation, do nothing 7 | if (!elem || !animation) return; 8 | 9 | // Remove the [hidden] attribute 10 | elem.removeAttribute('hidden'); 11 | 12 | // Apply the animation 13 | elem.classList.add(animation); 14 | 15 | // Detect when the animation ends 16 | elem.addEventListener('animationend', function endAnimation(event) { 17 | 18 | // Remove the animation class 19 | elem.classList.remove(animation); 20 | 21 | // If the element should be hidden, hide it 22 | if (hide) { 23 | elem.setAttribute('hidden', 'true'); 24 | } 25 | 26 | // Remove this event listener 27 | elem.removeEventListener('animationend', endAnimation, false); 28 | 29 | if (callback) { 30 | // Fire callback function 31 | callback(); 32 | } 33 | 34 | }, false); 35 | } -------------------------------------------------------------------------------- /animationEventListener.js: -------------------------------------------------------------------------------- 1 | var pfx = ["webkit", "moz", "MS", "o", ""]; 2 | function prefixedEventListener(element, type, callback) { 3 | for (var p = 0; p < pfx.length; p++) { 4 | if (!pfx[p]) type = type.toLowerCase(); 5 | element.addEventListener(pfx[p]+type, callback, false); 6 | } 7 | } 8 | 9 | // var monkey = document.querySelector("#monkey"); 10 | // prefixedEventListener(monkey,"AnimationStart",function(e){ 11 | // console.log("log at beginning of monkey animation"); 12 | // }); -------------------------------------------------------------------------------- /autoHideSticky.js: -------------------------------------------------------------------------------- 1 | var autoHideSticky = function( elem, inactiveClass, activeClass ) { 2 | // scrolled to the very top; element sticks to the top 3 | if ( wScrollCurrent <= 0 ) { 4 | elem.classList.remove(inactiveClass); 5 | elem.classList.remove(activeClass); 6 | 7 | // scrolled up; element slides in 8 | } else if ( wScrollDiff > 0 && elem.classList.contains(inactiveClass) ) { 9 | elem.classList.remove(inactiveClass); 10 | elem.classList.add(activeClass); 11 | } 12 | 13 | // scrolled down 14 | else if( wScrollDiff < 0 ) { 15 | 16 | // scrolled to the very bottom; element slides in 17 | if ( wScrollCurrent + wHeight >= dHeight && elem.classList.contains(inactiveClass) ) { 18 | elem.classList.remove( inactiveClass ); 19 | elem.classList.add(activeClass); 20 | } else { 21 | elem.classList.add(inactiveClass); 22 | elem.classList.remove(activeClass); 23 | } 24 | } 25 | 26 | wScrollBefore = wScrollCurrent; 27 | }; 28 | 29 | // Usage 30 | autoHideSticky(header, 'is-inactive', 'is-active'); -------------------------------------------------------------------------------- /bind.js: -------------------------------------------------------------------------------- 1 | var elem = document.querySelector('.some-class'); 2 | var someFunction = function (var1, var2, var3, event) { 3 | // Do stuff 4 | } 5 | elem.addEventListener('click', someFunction.bind(null, var1, var2, var3), false); 6 | elem.addEventListener('mouseover', someFunction.bind(null, var1, var2, var3), false); -------------------------------------------------------------------------------- /bindPolyfill.js: -------------------------------------------------------------------------------- 1 | if (!Function.prototype.bind) { 2 | Function.prototype.bind = function(oThis) { 3 | if (typeof this !== 'function') { 4 | // closest thing possible to the ECMAScript 5 5 | // internal IsCallable function 6 | throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); 7 | } 8 | 9 | var aArgs = Array.prototype.slice.call(arguments, 1), 10 | fToBind = this, 11 | fNOP = function() {}, 12 | fBound = function() { 13 | return fToBind.apply(this instanceof fNOP 14 | ? this 15 | : oThis, 16 | aArgs.concat(Array.prototype.slice.call(arguments))); 17 | }; 18 | 19 | if (this.prototype) { 20 | // native functions don't have a prototype 21 | fNOP.prototype = this.prototype; 22 | } 23 | fBound.prototype = new fNOP(); 24 | 25 | return fBound; 26 | }; 27 | } -------------------------------------------------------------------------------- /capitalizeEachWord.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Capitalize Each Word 3 | */ 4 | var capitalizeEachWord = function(string) { 5 | var splitStr = string.toLowerCase().split(' '); 6 | for (var i = 0; i < splitStr.length; i++) { 7 | splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1); 8 | } 9 | return splitStr.join(' '); 10 | }; -------------------------------------------------------------------------------- /checkActiveCategory.js: -------------------------------------------------------------------------------- 1 | var checkActiveCategory = function () { 2 | 3 | // Create Categories array 4 | var categories = []; 5 | 6 | // Loop through section headers 7 | forEach( sectionHeaders, function ( index ) { 8 | 9 | // If the section header is at the top of the page (minus category menu height) 10 | if ( wScrollCurrent >= ( index.offsetTop - navHeight ) - 5 ) { 11 | 12 | // Get section ID and add this id the Categories array 13 | var sectionId = index.parentNode.getAttribute( 'id' ); 14 | categories.push( sectionId ); 15 | 16 | } else { 17 | return; 18 | } 19 | 20 | }); 21 | 22 | // Get last item in Categories array 23 | var activeSection = categories[ categories.length - 1 ]; 24 | 25 | // Find the corresponding category nav link to the last item in the Categories array 26 | var activeSectionLink = categoryNav.querySelector('a[href="#' + activeSection + '"]'); 27 | 28 | // If there is an active section link, pass it into setActiveCategory() 29 | if ( activeSectionLink ) { 30 | resetActiveClass( activeSectionLink ); 31 | activeSectionLink.classList.add( activeClass ); 32 | } 33 | }; -------------------------------------------------------------------------------- /checkMedia.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Check if CSS media query has fired 3 | * 1. Pass in keywords to body:after content that via media query 4 | * 2. Detect this value in JS 5 | */ 6 | var checkMedia = function() { 7 | var media = window.getComputedStyle( body,':after' ).getPropertyValue( 'content' ); 8 | return removeQuotes( media ); 9 | }; 10 | 11 | // Usage (HTML) 12 | // body:after { 13 | // display: none; 14 | // content: 'small'; 15 | 16 | // @include media(">small") { 17 | // content: 'medium'; 18 | // } 19 | 20 | // @include media(">large") { 21 | // content: 'large'; 22 | // } 23 | // } 24 | 25 | // Usage (JS) 26 | if (checkMedia() === 'small') { 27 | // Run code 28 | } -------------------------------------------------------------------------------- /checkUrlHash.js: -------------------------------------------------------------------------------- 1 | var checkURL = (function() { 2 | if ( window.location.hash ) { 3 | var hash = window.location.hash.substring(1); 4 | if ( hash === 'newsletter' ) { 5 | var trigger = document.querySelector( '.intro__news' ).querySelector( 'a' ); 6 | trigger.click(); 7 | } 8 | } 9 | })(); -------------------------------------------------------------------------------- /checkVisibility.js: -------------------------------------------------------------------------------- 1 | var checkVisibility = function(elem) { 2 | var viewportSize = getViewportSize(); 3 | var currentScroll = getCurrentScroll(); 4 | var elemInfo = getElemInfo(elem); 5 | var spaceOffset = 0.2; 6 | var elemHeight = elemInfo.height; 7 | var elemWidth = elemInfo.width; 8 | var elemTop = elemInfo.top; 9 | var elemLeft = elemInfo.left; 10 | var elemBottom = elemTop + elemHeight; 11 | var elemRight = elemLeft + elemWidth; 12 | 13 | var checkBoundaries = function() { 14 | // Defining the element boundaries and extra space offset 15 | var top = elemTop + elemHeight * spaceOffset; 16 | var left = elemLeft + elemWidth * spaceOffset; 17 | var bottom = elemBottom - elemHeight * spaceOffset; 18 | var right = elemRight - elemWidth * spaceOffset; 19 | 20 | // Defining the window boundaries and window offset 21 | var wTop = currentScroll.y + 0; 22 | var wLeft = currentScroll.x + 0; 23 | var wBottom = currentScroll.y - 0 + viewportSize.height; 24 | var wRight = currentScroll.x - 0 + viewportSize.width; 25 | 26 | // Check if the element is within boundary 27 | return (top < wBottom) && (bottom > wTop) && (left > wLeft) && (right < wRight); 28 | }; 29 | 30 | return checkBoundaries(); 31 | }; -------------------------------------------------------------------------------- /classList-polyfill.js: -------------------------------------------------------------------------------- 1 | /* 2 | * classList.js: Cross-browser full element.classList implementation. 3 | * 2014-07-23 4 | * 5 | * By Eli Grey, http://eligrey.com 6 | * Public Domain. 7 | * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 8 | */ 9 | 10 | /*global self, document, DOMException */ 11 | 12 | /*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/ 13 | 14 | if ("document" in self) { 15 | 16 | // Full polyfill for browsers with no classList support 17 | if (!("classList" in document.createElement("_"))) { 18 | 19 | (function (view) { 20 | 21 | "use strict"; 22 | 23 | if (!('Element' in view)) return; 24 | 25 | var 26 | classListProp = "classList" 27 | , protoProp = "prototype" 28 | , elemCtrProto = view.Element[protoProp] 29 | , objCtr = Object 30 | , strTrim = String[protoProp].trim || function () { 31 | return this.replace(/^\s+|\s+$/g, ""); 32 | } 33 | , arrIndexOf = Array[protoProp].indexOf || function (item) { 34 | var 35 | i = 0 36 | , len = this.length 37 | ; 38 | for (; i < len; i++) { 39 | if (i in this && this[i] === item) { 40 | return i; 41 | } 42 | } 43 | return -1; 44 | } 45 | // Vendors: please allow content code to instantiate DOMExceptions 46 | , DOMEx = function (type, message) { 47 | this.name = type; 48 | this.code = DOMException[type]; 49 | this.message = message; 50 | } 51 | , checkTokenAndGetIndex = function (classList, token) { 52 | if (token === "") { 53 | throw new DOMEx( 54 | "SYNTAX_ERR" 55 | , "An invalid or illegal string was specified" 56 | ); 57 | } 58 | if (/\s/.test(token)) { 59 | throw new DOMEx( 60 | "INVALID_CHARACTER_ERR" 61 | , "String contains an invalid character" 62 | ); 63 | } 64 | return arrIndexOf.call(classList, token); 65 | } 66 | , ClassList = function (elem) { 67 | var 68 | trimmedClasses = strTrim.call(elem.getAttribute("class") || "") 69 | , classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [] 70 | , i = 0 71 | , len = classes.length 72 | ; 73 | for (; i < len; i++) { 74 | this.push(classes[i]); 75 | } 76 | this._updateClassName = function () { 77 | elem.setAttribute("class", this.toString()); 78 | }; 79 | } 80 | , classListProto = ClassList[protoProp] = [] 81 | , classListGetter = function () { 82 | return new ClassList(this); 83 | } 84 | ; 85 | // Most DOMException implementations don't allow calling DOMException's toString() 86 | // on non-DOMExceptions. Error's toString() is sufficient here. 87 | DOMEx[protoProp] = Error[protoProp]; 88 | classListProto.item = function (i) { 89 | return this[i] || null; 90 | }; 91 | classListProto.contains = function (token) { 92 | token += ""; 93 | return checkTokenAndGetIndex(this, token) !== -1; 94 | }; 95 | classListProto.add = function () { 96 | var 97 | tokens = arguments 98 | , i = 0 99 | , l = tokens.length 100 | , token 101 | , updated = false 102 | ; 103 | do { 104 | token = tokens[i] + ""; 105 | if (checkTokenAndGetIndex(this, token) === -1) { 106 | this.push(token); 107 | updated = true; 108 | } 109 | } 110 | while (++i < l); 111 | 112 | if (updated) { 113 | this._updateClassName(); 114 | } 115 | }; 116 | classListProto.remove = function () { 117 | var 118 | tokens = arguments 119 | , i = 0 120 | , l = tokens.length 121 | , token 122 | , updated = false 123 | , index 124 | ; 125 | do { 126 | token = tokens[i] + ""; 127 | index = checkTokenAndGetIndex(this, token); 128 | while (index !== -1) { 129 | this.splice(index, 1); 130 | updated = true; 131 | index = checkTokenAndGetIndex(this, token); 132 | } 133 | } 134 | while (++i < l); 135 | 136 | if (updated) { 137 | this._updateClassName(); 138 | } 139 | }; 140 | classListProto.toggle = function (token, force) { 141 | token += ""; 142 | 143 | var 144 | result = this.contains(token) 145 | , method = result ? 146 | force !== true && "remove" 147 | : 148 | force !== false && "add" 149 | ; 150 | 151 | if (method) { 152 | this[method](token); 153 | } 154 | 155 | if (force === true || force === false) { 156 | return force; 157 | } else { 158 | return !result; 159 | } 160 | }; 161 | classListProto.toString = function () { 162 | return this.join(" "); 163 | }; 164 | 165 | if (objCtr.defineProperty) { 166 | var classListPropDesc = { 167 | get: classListGetter 168 | , enumerable: true 169 | , configurable: true 170 | }; 171 | try { 172 | objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); 173 | } catch (ex) { // IE 8 doesn't support enumerable:true 174 | if (ex.number === -0x7FF5EC54) { 175 | classListPropDesc.enumerable = false; 176 | objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); 177 | } 178 | } 179 | } else if (objCtr[protoProp].__defineGetter__) { 180 | elemCtrProto.__defineGetter__(classListProp, classListGetter); 181 | } 182 | 183 | }(self)); 184 | 185 | } else { 186 | // There is full or partial native classList support, so just check if we need 187 | // to normalize the add/remove and toggle APIs. 188 | 189 | (function () { 190 | "use strict"; 191 | 192 | var testElement = document.createElement("_"); 193 | 194 | testElement.classList.add("c1", "c2"); 195 | 196 | // Polyfill for IE 10/11 and Firefox <26, where classList.add and 197 | // classList.remove exist but support only one argument at a time. 198 | if (!testElement.classList.contains("c2")) { 199 | var createMethod = function(method) { 200 | var original = DOMTokenList.prototype[method]; 201 | 202 | DOMTokenList.prototype[method] = function(token) { 203 | var i, len = arguments.length; 204 | 205 | for (i = 0; i < len; i++) { 206 | token = arguments[i]; 207 | original.call(this, token); 208 | } 209 | }; 210 | }; 211 | createMethod('add'); 212 | createMethod('remove'); 213 | } 214 | 215 | testElement.classList.toggle("c3", false); 216 | 217 | // Polyfill for IE 10 and Firefox <24, where classList.toggle does not 218 | // support the second argument. 219 | if (testElement.classList.contains("c3")) { 220 | var _toggle = DOMTokenList.prototype.toggle; 221 | 222 | DOMTokenList.prototype.toggle = function(token, force) { 223 | if (1 in arguments && !this.contains(token) === !force) { 224 | return force; 225 | } else { 226 | return _toggle.call(this, token); 227 | } 228 | }; 229 | 230 | } 231 | 232 | testElement = null; 233 | }()); 234 | 235 | } 236 | 237 | } -------------------------------------------------------------------------------- /classList.js: -------------------------------------------------------------------------------- 1 | /** 2 | * classList class methods 3 | */ 4 | 5 | // Adding a class 6 | element.classList.add("bar"); 7 | 8 | // Removing a class 9 | element.classList.remove("foo"); 10 | 11 | // Checking if has a class 12 | element.classList.contains("foo"); 13 | 14 | // Toggle a class 15 | element.classList.toggle("active"); -------------------------------------------------------------------------------- /closestParent.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Element} el 3 | * @param {string} selector 4 | * @param {boolean} [includeSelf] 5 | * @return {Element|null} 6 | */ 7 | 8 | closestParent = function(el, selector, includeSelf) { 9 | var parent = el.parentNode; 10 | 11 | if (includeSelf && el.matches(selector)) { 12 | return el; 13 | } 14 | 15 | while (parent && parent !== document.body) { 16 | if (parent.matches && parent.matches(selector)) { 17 | return parent; 18 | } else if (parent.parentNode) { 19 | parent = parent.parentNode; 20 | } else { 21 | return null; 22 | } 23 | } 24 | 25 | return null; 26 | }; -------------------------------------------------------------------------------- /cross-bowser-class-handlers.js: -------------------------------------------------------------------------------- 1 | var hasClass = function (elem, className) { 2 | return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' '); 3 | }; 4 | 5 | var addClass = function (elem, className) { 6 | if (!hasClass(elem, className)) { 7 | elem.className += ' ' + className; 8 | } 9 | }; 10 | 11 | var removeClass = function (elem, className) { 12 | var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, ' ') + ' '; 13 | if (hasClass(elem, className)) { 14 | while (newClass.indexOf(' ' + className + ' ') >= 0 ) { 15 | newClass = newClass.replace(' ' + className + ' ', ' '); 16 | } 17 | elem.className = newClass.replace(/^\s+|\s+$/g, ''); 18 | } 19 | }; 20 | 21 | var toggleClass = function(elem, className) { 22 | var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, ' ' ) + ' '; 23 | if (hasClass(elem, className)) { 24 | while (newClass.indexOf(' ' + className + ' ') >= 0 ) { 25 | newClass = newClass.replace( ' ' + className + ' ' , ' ' ); 26 | } 27 | elem.className = newClass.replace(/^\s+|\s+$/g, ''); 28 | } else { 29 | elem.className += ' ' + className; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /cssSupports.js: -------------------------------------------------------------------------------- 1 | // CSS Supports normalization 2 | var cssSupports = window.CSS && window.CSS.supports || window.supportsCSS; 3 | 4 | // Usage 5 | if ( cssSupports && cssSupports ('(transition: none)') ) { 6 | // CSS transitions are supported! 7 | } -------------------------------------------------------------------------------- /cutsMustard.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Cut the Mustard / Method A 3 | */ 4 | var supports = !!document.querySelector && !!window.addEventListener; 5 | if ( !supports ) return; 6 | 7 | 8 | /** 9 | * Cut the Mustard / Method B 10 | */ 11 | if ( 'querySelector' in document && 'addEventListener' in window && "classList" in document.documentElement ) { 12 | // Scripts go here 13 | } 14 | 15 | 16 | /** 17 | * Cut the Mustard / Method C 18 | */ 19 | if ( 'querySelector' in document && 'addEventListener' in window ) { 20 | document.documentElement.className += 'js'; 21 | } 22 | 23 | 24 | /** 25 | * Cut the Mustard / Method D 26 | * 1. Test for support 27 | * 2. Remove '.no-js' on with '.js' 28 | */ 29 | if (!document.querySelector && !window.addEventListener) { /* 1 */ 30 | return; 31 | } else { 32 | document.documentElement.className = "js"; /* 2 */ 33 | } 34 | 35 | 36 | /** 37 | * Cut the Mustard / Method E 38 | */ 39 | (function (win, doc) { 40 | if (!win.addEventListener) { 41 | return; 42 | } 43 | ... 44 | var enhanceclass = 'cutsthemustard'; 45 | doc.documentElement.className += ' ' + enhanceclass; 46 | }(this, this.document)); 47 | 48 | 49 | /** 50 | * Cut the Mustard / Method F 51 | */ 52 | var feature = { 53 | addEventListener : !!window.addEventListener, 54 | querySelectorAll : !!document.querySelectorAll, 55 | }; 56 | 57 | if (feature.addEventListener && feature.querySelectorAll) { 58 | this.init(); 59 | } -------------------------------------------------------------------------------- /debounce.js: -------------------------------------------------------------------------------- 1 | // Returns a function, that, as long as it continues to be invoked, will not 2 | // be triggered. The function will be called after it stops being called for 3 | // N milliseconds. If `immediate` is passed, trigger the function on the 4 | // leading edge, instead of the trailing. 5 | function debounce(func, wait, immediate) { 6 | var timeout; 7 | return function() { 8 | var context = this, args = arguments; 9 | var later = function() { 10 | timeout = null; 11 | if (!immediate) func.apply(context, args); 12 | }; 13 | var callNow = immediate && !timeout; 14 | clearTimeout(timeout); 15 | timeout = setTimeout(later, wait); 16 | if (callNow) func.apply(context, args); 17 | }; 18 | }; 19 | 20 | // Usage 21 | var myEfficientFn = debounce(function() { 22 | // All the taxing stuff you do 23 | }, 250); 24 | 25 | window.addEventListener('resize', myEfficientFn); -------------------------------------------------------------------------------- /delegate-event.js: -------------------------------------------------------------------------------- 1 | var functionName = function () { 2 | element.addEventListener( 'click', function( event ) { 3 | if( event.target && event.target.nodeName === 'A' ) { 4 | // Do Something 5 | } 6 | }); 7 | }; 8 | 9 | functionName(); -------------------------------------------------------------------------------- /event-polyfill.js: -------------------------------------------------------------------------------- 1 | // Polyfill event.preventDefault & event.addEventListener 2 | if (!window.addEventListener) { 3 | (function() { 4 | if (!Event.prototype.preventDefault) { 5 | Event.prototype.preventDefault=function() { 6 | this.returnValue=false; 7 | }; 8 | } 9 | if (!Event.prototype.stopPropagation) { 10 | Event.prototype.stopPropagation=function() { 11 | this.cancelBubble=true; 12 | }; 13 | } 14 | if (!Element.prototype.addEventListener) { 15 | var eventListeners=[]; 16 | var addEventListener=function(type,listener /*, useCapture (will be ignored) */) { 17 | var self=this; 18 | var wrapper=function(e) { 19 | e.target=e.srcElement; 20 | e.currentTarget=self; 21 | if (listener.handleEvent) { 22 | listener.handleEvent(e); 23 | } else { 24 | listener.call(self,e); 25 | } 26 | }; 27 | if (type=="DOMContentLoaded") { 28 | var wrapper2=function(e) { 29 | if (document.readyState=="complete") { 30 | wrapper(e); 31 | } 32 | }; 33 | document.attachEvent("onreadystatechange",wrapper2); 34 | eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper2}); 35 | if (document.readyState=="complete") { 36 | var e=new Event(); 37 | e.srcElement=window; 38 | wrapper2(e); 39 | } 40 | } else { 41 | this.attachEvent("on"+type,wrapper); 42 | eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper}); 43 | } 44 | }; 45 | var removeEventListener=function(type,listener /*, useCapture (will be ignored) */) { 46 | var counter=0; 47 | while (counter'; 52 | head.appendChild(div.childNodes[1]); 53 | }; 54 | 55 | fluidvids.render = function () { 56 | var nodes = document.querySelectorAll(fluidvids.selector.join()); 57 | var i = nodes.length; 58 | while (i--) { 59 | fluid(nodes[i]); 60 | } 61 | }; 62 | 63 | fluidvids.init = function (obj) { 64 | for (var key in obj) { 65 | fluidvids[key] = obj[key]; 66 | } 67 | fluidvids.render(); 68 | addStyles(); 69 | }; 70 | 71 | return fluidvids; 72 | 73 | }); -------------------------------------------------------------------------------- /forEach.js: -------------------------------------------------------------------------------- 1 | // Production steps of ECMA-262, Edition 5, 15.4.4.18 2 | // Reference: http://es5.github.io/#x15.4.4.18 3 | if (!Array.prototype.forEach) { 4 | 5 | Array.prototype.forEach = function(callback, thisArg) { 6 | 7 | var T, k; 8 | 9 | if (this == null) { 10 | throw new TypeError(' this is null or not defined'); 11 | } 12 | 13 | // 1. Let O be the result of calling ToObject passing the |this| value as the argument. 14 | var O = Object(this); 15 | 16 | // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". 17 | // 3. Let len be ToUint32(lenValue). 18 | var len = O.length >>> 0; 19 | 20 | // 4. If IsCallable(callback) is false, throw a TypeError exception. 21 | // See: http://es5.github.com/#x9.11 22 | if (typeof callback !== "function") { 23 | throw new TypeError(callback + ' is not a function'); 24 | } 25 | 26 | // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. 27 | if (arguments.length > 1) { 28 | T = thisArg; 29 | } 30 | 31 | // 6. Let k be 0 32 | k = 0; 33 | 34 | // 7. Repeat, while k < len 35 | while (k < len) { 36 | 37 | var kValue; 38 | 39 | // a. Let Pk be ToString(k). 40 | // This is implicit for LHS operands of the in operator 41 | // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk. 42 | // This step can be combined with c 43 | // c. If kPresent is true, then 44 | if (k in O) { 45 | 46 | // i. Let kValue be the result of calling the Get internal method of O with argument Pk. 47 | kValue = O[k]; 48 | 49 | // ii. Call the Call internal method of callback with T as the this value and 50 | // argument list containing kValue, k, and O. 51 | callback.call(T, kValue, k, O); 52 | } 53 | // d. Increase k by 1. 54 | k++; 55 | } 56 | // 8. return undefined 57 | }; 58 | } -------------------------------------------------------------------------------- /forEachLoop.js: -------------------------------------------------------------------------------- 1 | [].forEach.call(element, function(el) { 2 | el.addEventListener('click', fnName, false); 3 | }); -------------------------------------------------------------------------------- /get-anchor.js: -------------------------------------------------------------------------------- 1 | var anchor = event.target; 2 | 3 | // Go up in the nodelist until we find a node with .href (HTMLAnchorElement) 4 | while ( anchor && !anchor.href ) { 5 | anchor = anchor.parentNode; 6 | } -------------------------------------------------------------------------------- /get-widths-from-list.js: -------------------------------------------------------------------------------- 1 | let itemWidths = Array.from(item).map(function (item) { 2 | return item.offsetWidth; 3 | }); -------------------------------------------------------------------------------- /getAbsoluteUrl.js: -------------------------------------------------------------------------------- 1 | var getAbsoluteUrl = (function() { 2 | var a; 3 | 4 | return function(url) { 5 | if(!a) a = document.createElement('a'); 6 | a.href = url; 7 | 8 | return a.href; 9 | }; 10 | })(); 11 | 12 | // Usage 13 | getAbsoluteUrl('/something'); // https://davidwalsh.name/something -------------------------------------------------------------------------------- /getClosest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get the closest matching element up the DOM tree. 3 | * @private 4 | * @param {Element} elem Starting element 5 | * @param {String} selector Selector to match against 6 | * @return {Boolean|Element} Returns null if not match found 7 | */ 8 | var getClosest = function ( elem, selector ) { 9 | 10 | // Element.matches() polyfill 11 | if (!Element.prototype.matches) { 12 | Element.prototype.matches = 13 | Element.prototype.matchesSelector || 14 | Element.prototype.mozMatchesSelector || 15 | Element.prototype.msMatchesSelector || 16 | Element.prototype.oMatchesSelector || 17 | Element.prototype.webkitMatchesSelector || 18 | function(s) { 19 | var matches = (this.document || this.ownerDocument).querySelectorAll(s), 20 | i = matches.length; 21 | while (--i >= 0 && matches.item(i) !== this) {} 22 | return i > -1; 23 | }; 24 | } 25 | 26 | // Get closest match 27 | for ( ; elem && elem !== document; elem = elem.parentNode ) { 28 | if ( elem.matches( selector ) ) return elem; 29 | } 30 | 31 | return null; 32 | 33 | }; 34 | 35 | var elem = document.querySelector( '#some-element' ); 36 | var closest = getClosest( elem, '.some-class' ); 37 | var closestLink = getClosest( elem, 'a' ); 38 | var closestExcludingElement = getClosest( elem.parentNode, '.some-class' ); -------------------------------------------------------------------------------- /getClosestAlt.js: -------------------------------------------------------------------------------- 1 | const getClosest = function (elem, selector) { 2 | for (; elem && elem !== document; elem = elem.parentNode) { 3 | if (elem.matches(selector)) return elem; 4 | } 5 | return null; 6 | }; -------------------------------------------------------------------------------- /getComputedStyle.js: -------------------------------------------------------------------------------- 1 | window.getComputedStyle(header,null).getPropertyValue('top') -------------------------------------------------------------------------------- /getCurrentScroll.js: -------------------------------------------------------------------------------- 1 | var getCurrentScroll = function() { 2 | return { 3 | x: window.pageXOffset, 4 | y: window.pageYOffset 5 | }; 6 | }; -------------------------------------------------------------------------------- /getDocumentHeight.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get the height of the `document` element 3 | * @return {Number} The height 4 | */ 5 | var getDocumentHeight = function () { 6 | return Math.max( 7 | document.body.scrollHeight, 8 | document.documentElement.scrollHeight, 9 | document.body.offsetHeight, 10 | document.documentElement.offsetHeight, 11 | document.body.clientHeight, 12 | document.documentElement.clientHeight 13 | ); 14 | }; -------------------------------------------------------------------------------- /getElemDistance.js: -------------------------------------------------------------------------------- 1 | // Get current location's distance from the top of the page 2 | var position = window.pageYOffset; 3 | 4 | /** 5 | * Get an element's distance from the top of the page 6 | * @param {Node} elem The element 7 | * @return {Number} Distance from the top of the page 8 | */ 9 | var getElemDistance = function ( elem ) { 10 | var location = 0; 11 | if ( elem.offsetParent ) { 12 | do { 13 | location += elem.offsetTop; 14 | elem = elem.offsetParent; 15 | } while ( elem ); 16 | } 17 | return location >= 0 ? location : 0; 18 | }; 19 | var elem = document.querySelector( '#some-element' ); 20 | var location = getElemDistance( elem ); -------------------------------------------------------------------------------- /getElemInfo.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get the element’s dimensions and position 3 | */ 4 | var getElemInfo = function(elem) { 5 | var offsetTop = 0; 6 | var offsetLeft = 0; 7 | var offsetHeight = elem.offsetHeight; 8 | var offsetWidth = elem.offsetWidth; 9 | 10 | do { 11 | if (!isNaN(elem.offsetTop)) { 12 | offsetTop += elem.offsetTop; 13 | } 14 | if (!isNaN(elem.offsetLeft)) { 15 | offsetLeft += elem.offsetLeft; 16 | } 17 | } while ((elem = elem.offsetParent) !== null); 18 | 19 | return { 20 | top: offsetTop, 21 | left: offsetLeft, 22 | height: offsetHeight, 23 | width: offsetWidth 24 | }; 25 | }; -------------------------------------------------------------------------------- /getHeight.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get the height of an element 3 | * @param {Node} elem The element 4 | * @return {Number} The height 5 | */ 6 | var getHeight = function ( elem ) { 7 | return Math.max( elem.scrollHeight, elem.offsetHeight, elem.clientHeight ); 8 | }; 9 | 10 | var elem = document.querySelector( '#some-element' ); 11 | var height = getHeight( elem ); // Get height 12 | elem.style.height = '200px'; // Set height -------------------------------------------------------------------------------- /getIndex.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Element} el 3 | * @param {string} [selector] 4 | * @return {number} 5 | */ 6 | 7 | getIndex = function(el, selector) { 8 | var i = 0; 9 | 10 | while ((el = el.previousElementSibling) !== null) { 11 | if (!selector || el.matches(selector)) { 12 | ++i; 13 | } 14 | } 15 | 16 | return i; 17 | }; -------------------------------------------------------------------------------- /getJSONP.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get JSONP data 3 | * @param {String} url The JSON URL 4 | * @param {Function} callback The function to run after JSONP data loaded 5 | */ 6 | var getJSONP = function ( url, callback ) { 7 | 8 | // Create script with url and callback (if specified) 9 | var ref = window.document.getElementsByTagName( 'script' )[ 0 ]; 10 | var script = window.document.createElement( 'script' ); 11 | script.src = url + (url.indexOf( '?' ) + 1 ? '&' : '?') + 'callback=' + callback; 12 | 13 | // Insert script tag into the DOM (append to ) 14 | ref.parentNode.insertBefore( script, ref ); 15 | 16 | // After the script is loaded (and executed), remove it 17 | script.onload = function () { 18 | this.remove(); 19 | }; 20 | 21 | }; 22 | 23 | // Example 24 | var logAPI = function ( data ) { 25 | console.log( data ); 26 | } 27 | getJSONP( 'http://api.petfinder.com/shelter.getPets?format=json&key=12345&shelter=AA11', 'logAPI' ); -------------------------------------------------------------------------------- /getMaxWidth.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get image's max-width:100%; in pixels 3 | */ 4 | function getMaxWidth(img) { 5 | var maxWidth; 6 | 7 | // Check if naturalWidth is supported 8 | if (img.naturalWidth !== undefined) { 9 | maxWidth = img.naturalWidth; 10 | 11 | // Not supported, use in-memory solution as fallback 12 | } else { 13 | var image = new Image(); 14 | image.src = img.src; 15 | maxWidth = image.width; 16 | } 17 | 18 | // Return the max-width 19 | return maxWidth; 20 | } 21 | 22 | // Make sure images are fully loaded before checking widths 23 | function hasDimensions(img) { 24 | return !!((img.complete && typeof img.naturalWidth !== "undefined") || img.width); 25 | } -------------------------------------------------------------------------------- /getNextSibling.js: -------------------------------------------------------------------------------- 1 | const getNextSibling = function (elem, selector) { 2 | 3 | // Get the next sibling element 4 | let sibling = elem.nextElementSibling; 5 | 6 | // If there's no selector, return the first sibling 7 | if (!selector) return sibling; 8 | 9 | // If the sibling matches our selector, use it 10 | // If not, jump to the next sibling and continue the loop 11 | while (sibling) { 12 | if (sibling.matches(selector)) return sibling; 13 | sibling = sibling.nextElementSibling 14 | } 15 | 16 | }; -------------------------------------------------------------------------------- /getNextUntil.js: -------------------------------------------------------------------------------- 1 | const getNextUntil = function (elem, selector) { 2 | 3 | // Setup siblings array and get next sibling 4 | var siblings = []; 5 | var next = elem.nextElementSibling; 6 | 7 | // Loop through all siblings 8 | while (next) { 9 | 10 | // If the matching item is found, quit 11 | if (selector && next.matches(selector)) break; 12 | 13 | // Otherwise, push to array 14 | siblings.push(next); 15 | 16 | // Get the next sibling 17 | next = next.nextElementSibling 18 | 19 | } 20 | 21 | return siblings; 22 | 23 | }; -------------------------------------------------------------------------------- /getPageName.js: -------------------------------------------------------------------------------- 1 | var pageName = window.location.pathname.substring(1).split(/[/.]+/g)[0]; -------------------------------------------------------------------------------- /getParents.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get all of an element's parent elements up the DOM tree 3 | * @param {Node} elem The element 4 | * @param {String} selector A class, ID, data attribute or tag to filter against [optional] 5 | * @return {Array} The parent elements 6 | */ 7 | var getParents = function ( elem, selector ) { 8 | 9 | // Element.matches() polyfill 10 | if (!Element.prototype.matches) { 11 | Element.prototype.matches = 12 | Element.prototype.matchesSelector || 13 | Element.prototype.mozMatchesSelector || 14 | Element.prototype.msMatchesSelector || 15 | Element.prototype.oMatchesSelector || 16 | Element.prototype.webkitMatchesSelector || 17 | function(s) { 18 | var matches = (this.document || this.ownerDocument).querySelectorAll(s), 19 | i = matches.length; 20 | while (--i >= 0 && matches.item(i) !== this) {} 21 | return i > -1; 22 | }; 23 | } 24 | 25 | // Setup parents array 26 | var parents = []; 27 | 28 | // Get matching parent elements 29 | for ( ; elem && elem !== document; elem = elem.parentNode ) { 30 | 31 | // Add matching parents to array 32 | if ( selector ) { 33 | if ( elem.matches( selector ) ) { 34 | parents.push( elem ); 35 | } 36 | } else { 37 | parents.push( elem ); 38 | } 39 | 40 | } 41 | 42 | return parents; 43 | 44 | }; 45 | 46 | var elem = document.querySelector( '#some-element' ); 47 | var parents = getParents( elem, '.some-class' ); 48 | var allParents = getParents( elem.parentNode ); -------------------------------------------------------------------------------- /getParentsUntil.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get all of an element's parent elements up the DOM tree until a matching parent is found 3 | * @param {Node} elem The element 4 | * @param {String} parent The selector for the parent to stop at 5 | * @param {String} selector The selector to filter against [optionals] 6 | * @return {Array} The parent elements 7 | */ 8 | var getParentsUntil = function ( elem, parent, selector ) { 9 | 10 | // Element.matches() polyfill 11 | if (!Element.prototype.matches) { 12 | Element.prototype.matches = 13 | Element.prototype.matchesSelector || 14 | Element.prototype.mozMatchesSelector || 15 | Element.prototype.msMatchesSelector || 16 | Element.prototype.oMatchesSelector || 17 | Element.prototype.webkitMatchesSelector || 18 | function(s) { 19 | var matches = (this.document || this.ownerDocument).querySelectorAll(s), 20 | i = matches.length; 21 | while (--i >= 0 && matches.item(i) !== this) {} 22 | return i > -1; 23 | }; 24 | } 25 | 26 | // Setup parents array 27 | var parents = []; 28 | 29 | // Get matching parent elements 30 | for ( ; elem && elem !== document; elem = elem.parentNode ) { 31 | 32 | if ( parent ) { 33 | if ( elem.matches( parent ) ) break; 34 | } 35 | 36 | if ( selector ) { 37 | if ( elem.matches( selector ) ) { 38 | parents.push( elem ); 39 | } 40 | break; 41 | } 42 | 43 | parents.push( elem ); 44 | 45 | } 46 | 47 | return parents; 48 | 49 | }; 50 | 51 | // Examples 52 | var elem = document.querySelector( '#some-element' ); 53 | var parentsUntil = getParentsUntil( elem, '.some-class' ); 54 | var parentsUntilByFilter = getParentsUntil( elem, '.some-class', '[data-something]' ); 55 | var allParentsUntil = getParentsUntil( elem ); 56 | var allParentsExcludingElem = getParentsUntil( elem.parentNode ); -------------------------------------------------------------------------------- /getPreviousSibling.js: -------------------------------------------------------------------------------- 1 | const getPreviousSibling = function (elem, selector) { 2 | 3 | // Get the next sibling element 4 | let sibling = elem.previousElementSibling; 5 | 6 | // If there's no selector, return the first sibling 7 | if (!selector) return sibling; 8 | 9 | // If the sibling matches our selector, use it 10 | // If not, jump to the next sibling and continue the loop 11 | while (sibling) { 12 | if (sibling.matches(selector)) return sibling; 13 | sibling = sibling.previousElementSibling; 14 | } 15 | 16 | }; -------------------------------------------------------------------------------- /getPreviousUntil.js: -------------------------------------------------------------------------------- 1 | var getPreviousUntil = function (elem, selector) { 2 | 3 | // Setup siblings array and get previous sibling 4 | var siblings = []; 5 | var prev = elem.previousElementSibling; 6 | 7 | // Loop through all siblings 8 | while (prev) { 9 | 10 | // If the matching item is found, quit 11 | if (selector && prev.matches(selector)) break; 12 | 13 | // Otherwise, push to array 14 | siblings.push(prev); 15 | 16 | // Get the previous sibling 17 | prev = prev.previousElementSibling 18 | 19 | } 20 | 21 | return siblings; 22 | 23 | }; -------------------------------------------------------------------------------- /getQueryString.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get the value of a query string from a URL 3 | * @param {String} field The field to get the value of 4 | * @param {String} url The URL to get the value from [optional] 5 | * @return {String} The value 6 | */ 7 | var getQueryString = function ( field, url ) { 8 | var href = url ? url : window.location.href; 9 | var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' ); 10 | var string = reg.exec(href); 11 | return string ? string[1] : null; 12 | }; 13 | 14 | // http://example.com&this=chicken&that=sandwich 15 | var thisOne = getQueryString( 'this' ); // returns 'chicken' 16 | var thatOne = getQueryString( 'that' ); // returns 'sandwich' 17 | var anotherOne = getQueryString( 'another' ); // returns null 18 | var yetAnotherOne = getQueryString( 'example', 'http://another-example.com&example=something' ); // returns 'something' -------------------------------------------------------------------------------- /getSiblings.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get all siblings of an element 3 | * @param {Node} elem The element 4 | * @return {Array} The siblings 5 | */ 6 | var getSiblings = function ( elem ) { 7 | var siblings = []; 8 | var sibling = elem.parentNode.firstChild; 9 | for ( ; sibling; sibling = sibling.nextSibling ) { 10 | if ( sibling.nodeType === 1 && sibling !== elem ) { 11 | siblings.push( sibling ); 12 | } 13 | } 14 | return siblings; 15 | }; 16 | 17 | var elem = document.querySelector( '#some-element' ); 18 | var siblings = getSiblings( elem ); -------------------------------------------------------------------------------- /getSupportedPropertyName.js: -------------------------------------------------------------------------------- 1 | var getSupportedPropertyName = function(properties) { 2 | for (var i = 0; i < properties.length; i++) { 3 | if (typeof document.body.style[properties[i]] !== 'undefined') { 4 | return properties[i]; 5 | } 6 | } 7 | return null; 8 | }; 9 | 10 | var transform = ['transform', 'msTransform', 'webkitTransform', 'mozTransform', 'oTransform']; 11 | 12 | // Usage 13 | elem.style[getSupportedPropertyName(transform)] = 'translate3d(0px,' + Math.round(wScrollCurrent * rate) + 'px, 0px)'; -------------------------------------------------------------------------------- /getSvgSprite.js: -------------------------------------------------------------------------------- 1 | var ajax = new XMLHttpRequest(); 2 | ajax.open("GET", "svg/sprite.svg", true); 3 | ajax.send(); 4 | ajax.onload = function(e) { 5 | var div = document.createElement("div"); 6 | div.innerHTML = ajax.responseText; 7 | document.body.insertBefore(div, document.body.childNodes[0]); 8 | } -------------------------------------------------------------------------------- /getURL.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get HTML from another URL 3 | * @param {String} url The URL 4 | * @param {Function} success Callback on success 5 | * @param {Function} error Callback on failure 6 | */ 7 | var getURL = function ( url, success, error ) { 8 | 9 | // Feature detection 10 | if ( !window.XMLHttpRequest ) return; 11 | 12 | // Create new request 13 | var request = new XMLHttpRequest(); 14 | 15 | // Setup callbacks 16 | request.onreadystatechange = function () { 17 | 18 | // If the request is complete 19 | if ( request.readyState === 4 ) { 20 | 21 | // If the request failed 22 | if ( request.status !== 200 ) { 23 | if ( error && typeof error === 'function' ) { 24 | error( request.responseText, request ); 25 | } 26 | return; 27 | } 28 | 29 | // If the request succeeded 30 | if ( success && typeof success === 'function' ) { 31 | success( request.responseText, request ); 32 | } 33 | } 34 | 35 | }; 36 | 37 | // Get the HTML 38 | request.open( 'GET', url ); 39 | request.send(); 40 | 41 | }; 42 | 43 | // Example 1: Generic Example 44 | getURL( 45 | '/about', 46 | function (data) { 47 | // On success... 48 | var div = document.createElement( 'div' ); 49 | 50 | }, 51 | function (data) { 52 | // On failure... 53 | } 54 | ); 55 | 56 | // Example 2: Find a specific element in the HTML and inject it into the current page 57 | getURL( 58 | '/about', 59 | function (data) { 60 | 61 | // Create a div and inject the HTML into it 62 | var div = document.createElement( 'div' ); 63 | div.innerHTML = data; 64 | 65 | // Find the element you're looking for in the div 66 | var elem = div.querySelector( '#some-element' ); 67 | var location = document.querySelector( '#another-element' ); 68 | 69 | // Quit if the element or the place where you want to inject it don't exist 70 | if ( !elem || !location ) return; 71 | 72 | // Inject the element into the DOM 73 | location.innerHTML = elem.innerHTML; 74 | 75 | } 76 | ); -------------------------------------------------------------------------------- /getViewportSize.js: -------------------------------------------------------------------------------- 1 | var getViewportSize = function() { 2 | return { 3 | width: window.document.documentElement.clientWidth, 4 | height: window.document.documentElement.clientHeight 5 | }; 6 | }; -------------------------------------------------------------------------------- /handleEvent.js: -------------------------------------------------------------------------------- 1 | /** 2 | * handleEvent 3 | * Take an object as a second argument 4 | * Look for a method called "handleEvent" 5 | * Call handleEvent method 6 | * Ref: http://www.thecssninja.com/javascript/handleevent 7 | */ 8 | var object = { 9 | init: function() { 10 | button.addEventListener("click", this, false); 11 | button.addEventListener("touchstart", this, false); 12 | }, 13 | handleEvent: function(e) { 14 | switch(e.type) { 15 | case "click": 16 | this.action(); 17 | break; 18 | case "touchstart": 19 | this.action(); 20 | break; 21 | } 22 | }, 23 | action: function() { 24 | alert("Clicked or touched!"); 25 | } 26 | }; 27 | 28 | // Init 29 | object.init(); -------------------------------------------------------------------------------- /hasClass.js: -------------------------------------------------------------------------------- 1 | // hasClass, takes two params: element and classname 2 | function hasClass(el, cls) { 3 | return el.className && new RegExp("(\\s|^)" + cls + "(\\s|$)").test(el.className); 4 | } -------------------------------------------------------------------------------- /iconsFallback.js: -------------------------------------------------------------------------------- 1 | var supportsSvg = function() { 2 | var div = document.createElement('div'); 3 | div.innerHTML = ''; 4 | return (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg'; 5 | }; 6 | 7 | var iconsFallback = function() { 8 | 9 | // Get all SVGs on the page and how many there are 10 | var svgs = document.getElementsByTagName('svg'), 11 | svgL = svgs.length; 12 | 13 | // Loop through all SVGs on the page 14 | while( svgL-- ) { 15 | 16 | // If SVG isn't the first one, continue ... 17 | if(svgL > 0) { 18 | 19 | // Get title attribute of SVG 20 | var svgTitle = svgs[svgL].getAttribute('title'); 21 | 22 | // Get all elements from each SVG 23 | var uses = svgs[svgL].getElementsByTagName('use'), 24 | usesL = uses.length; 25 | 26 | // Loop through all elements within an SVG 27 | while( usesL-- ) { 28 | 29 | // Get the 'xlink:href' attributes 30 | var svgId = uses[usesL].getAttribute('xlink:href'); 31 | 32 | // Remove first character from variable (This removes the #) 33 | svgId = svgId.substring(1, svgId.length); 34 | 35 | // Create New Image 36 | var newImg = document.createElement('img'); 37 | 38 | // Assign src attribute 39 | newImg.src = 'assets/dist/icons/png/' + svgId + '.png'; 40 | 41 | // Assign alt attribute 42 | newImg.alt = svgTitle ? svgTitle : ''; 43 | 44 | // Insert new element straight after the SVG in question 45 | svgs[svgL].parentNode.insertBefore(newImg, svgs[svgL].nextSibling); 46 | 47 | } 48 | 49 | // Remove all SVG nodes 50 | svgs[svgL].parentNode.removeChild(svgs[svgL]); 51 | } 52 | } 53 | }; 54 | 55 | // Call iconsFallback method if SVG support test fails 56 | if ( !supportsSvg() ) { iconsFallback(); } -------------------------------------------------------------------------------- /iife.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Immediately Invoked Function Expression Boilerplate 3 | * (c) 2017 Chris Ferdinandi, MIT License, https://gomakethings.com 4 | */ 5 | ;(function (window, document, undefined) { 6 | 7 | 'use strict'; 8 | 9 | // Code goes here... 10 | 11 | })(window, document); 12 | -------------------------------------------------------------------------------- /insertRule.js: -------------------------------------------------------------------------------- 1 | var sheet = (function() { 2 | // Create the