Skip to content

Instantly share code, notes, and snippets.

@matthewmorek
Last active March 6, 2018 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewmorek/d6a11b04523b21ea81a727693775300c to your computer and use it in GitHub Desktop.
Save matthewmorek/d6a11b04523b21ea81a727693775300c to your computer and use it in GitHub Desktop.
Handy JavaScript polyfils
/**
* Barebones OS detection
* @return {OSName} string - contains OS alias
*/
var platform = function () {
'use strict';
var OSName="generic";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="win";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="mac";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="nix";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="nix";
return OSName;
};
/**
* forEach polyfil
* @param {Array} array - an array of elements to process
* @param {Function} callback - evaluation callback
* @param {thisArg} scope - callback scope
*/
var forEach = function (array, callback, scope) {
'use strict';
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
/**
* Utility method for binding events programmatically
* @param {Element} element - and element to bind event to
* @param {String} type - event type
* @param {Function} handler - callback function for the event
*/
var bindEvent = function (element, type, handler) {
'use strict';
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on' + type, handler);
}
};
/**
* Utility method to allow chaining of el.classList methods
* @param {Element} element - an element to bind new methods to
*/
var classList = function (el) {
var list = el.classList;
return {
toggle: function (c) { list.toggle(c); return this; },
add: function (c) { list.add(c); return this; },
remove: function (c) { list.remove(c); return this; }
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment