Skip to content

Instantly share code, notes, and snippets.

@samin
Last active August 29, 2015 14:01
Show Gist options
  • Save samin/796cd8f66c525b6b8380 to your computer and use it in GitHub Desktop.
Save samin/796cd8f66c525b6b8380 to your computer and use it in GitHub Desktop.
/**
The MIT License (MIT)
Copyright (c) 2014 Samin Shams
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**/
var _ = {
hasXHR: 'XMLHttpRequest' in window,
toString: Object.prototype.toString,
hasOwn: Object.prototype.hasOwnProperty,
push: Array.prototype.push,
slice: Array.prototype.slice,
trim: String.prototype.trim,
indexOf: Array.prototype.indexOf,
class2type: {
"[object Boolean]": "boolean",
"[object Number]": "number",
"[object String]": "string",
"[object Function]": "function",
"[object Array]": "array",
"[object Date]": "date",
"[object RegExp]": "regexp",
"[object Object]": "object"
},
isFunction: function (obj) {
return _.type(obj) === "function";
},
isArray: Array.isArray || function (obj) {
return _.type(obj) === "array";
},
isWindow: function (obj) {
return obj !== null && obj == obj.window;
},
isNumeric: function (obj) {
return !isNaN(parseFloat(obj)) && isFinite(obj);
},
type: function (obj) {
return obj === null ? String(obj) : _.class2type[_.toString.call(obj)] || "object";
},
isPlainObject: function (obj) {
if (!obj || _.type(obj) !== "object" || obj.nodeType) {
return false;
}
try {
if (obj.constructor && !_.hasOwn.call(obj, "constructor") && !_.hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
} catch (e) {
return false;
}
var key;
for (key in obj) {}
return key === undefined || _.hasOwn.call(obj, key);
},
isEmpty: function(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
},
domLoaded: function(callback) {
/* Mozilla, Chrome, Opera */
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', callback, false);
}
/* Safari, iCab, Konqueror */
else if (/KHTML|WebKit|iCab/i.test(navigator.userAgent)) {
var DOMLoadTimer = setInterval(function () {
if (/loaded|complete/i.test(document.readyState)) {
callback();
clearInterval(DOMLoadTimer);
}
}, 10);
} else {
/* Other web browsers */
window.onload = callback;
}
},
hasClass: function(elem, value, action) {
var classNames, ind;
if (elem.nodeType === 1) {
classNames = elem.className.split(' ');
ind = classNames.indexOf(value);
if (ind == -1) {
if (action == 'add' || action == 'toggle') {
classNames.push(value);
} else {
return false;
}
} else {
if (action == 'remove' || action == 'toggle') {
classNames.splice(ind, 1);
} else {
return true;
}
}
elem.className = classNames.join(' ');
}
},
addClass: function(elem, value) {
_.hasClass(elem, value, 'add');
},
removeClass: function(elem, value) {
_.hasClass(elem, value, 'remove');
},
toggleClass: function(elem, value) {
_.hasClass(elem, value, 'toggle');
},
getIndex: function(a, b) { //helper function (see below)
var i = 0, l = a.length;
for (i = 0, len = l; i < len; i ++) {
if(a[i] == b) return i;
}
return false;
},
matchUp: function(elem, selector, parent) {
var all, cur;
if (typeof selector == 'string') {
all = (parent) ? parent.querySelectorAll(selector) : document.querySelectorAll(selector);
} else {
all = selector;
}
cur = elem;
while(cur && _.getIndex(all, cur) === false) { //keep going up until you find a match
cur = cur.parentNode; //go up
}
return cur; //will return null if not found
},
findParent: function(elem, selector) {
return _.matchUp(elem.parentNode, selector);
},
html: function(elem, html, action) {
if (!action) action = 'inner';
if (typeof html === 'object') {
var l = html.length;
if (typeof l == 'undefined') {
html[0] = html;
l = 1;
}
if (action == 'inner') elem.innerHTML = '';
while (l--) {
if (action == 'replace') elem.replaceChild(html[0]);
else if (action == 'prepend') elem.insertBefore(html[0]);
else elem.appendChild(html[0]);
}
if (action == 'after') {
elem.parentNode.insertBefore(html[0], elem.nextSibling);
}
} else if (typeof html === 'string') {
if (action == 'append') elem.innerHTML += html;
else if (action == 'prepend') elem.innerHTML = html + elem.innerHTML;
else if (action == 'replace') elem.outerHTML = html;
else elem.innerHTML = html;
}
},
offset: function(obj) {
var curleft = obj.offsetLeft, curtop = obj.offsetTop;
if (obj.offsetParent) {
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
}
}
return {left:curleft,top:curtop};
},
serialize: function(form) {
'use strict';
var i, j, len, jLen, formElement, q = [],
urlencode = function(str) {
// http://kevin.vanzonneveld.net
// Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
// PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
},
addNameValue = function(name, value) {
q.push(urlencode(name) + '=' + urlencode(value));
};
if (!form || !form.nodeName || form.nodeName.toLowerCase() !== 'form') {
throw 'You must supply a form element';
}
i = form.elements.length;
while (i--) {
formElement = form.elements[i];
if (formElement.name === '' || formElement.disabled) {
continue;
}
}
for (i = 0, len = form.elements.length; i < len; i++) {
formElement = form.elements[i];
if (formElement.name === '' || formElement.disabled) {
continue;
}
switch (formElement.nodeName.toLowerCase()) {
case 'input':
switch (formElement.type) {
case 'text':
case 'hidden':
case 'password':
case 'button': // Not submitted when submitting form manually, though jQuery does serialize this and it can be an HTML4 successful control
case 'submit':
addNameValue(formElement.name, formElement.value);
break;
case 'checkbox':
case 'radio':
if (formElement.checked) {
addNameValue(formElement.name, formElement.value);
}
break;
case 'file':
// addNameValue(formElement.name, formElement.value); // Will work and part of HTML4 "successful controls", but not used in jQuery
break;
case 'reset':
break;
}
break;
case 'textarea':
addNameValue(formElement.name, formElement.value);
break;
case 'select':
switch (formElement.type) {
case 'select-one':
addNameValue(formElement.name, formElement.value);
break;
case 'select-multiple':
for (j = 0, jLen = formElement.options.length; j < jLen; j++) {
if (formElement.options[j].selected) {
addNameValue(formElement.name, formElement.options[j].value);
}
}
break;
}
break;
case 'button': // jQuery does not submit these, though it is an HTML4 successful control
switch (formElement.type) {
case 'reset':
case 'submit':
case 'button':
addNameValue(formElement.name, formElement.value);
break;
}
break;
}
}
return q.join('&');
},
extend: function() {
var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
i = 2;
}
if (typeof target !== "object" && !_.isFunction(target)) {
target = {};
}
if (length === i) {
target = this;
--i;
}
for (var j = i; j < length; j++) {
if ((options = arguments[j]) !== null) {
for (name in options) {
src = target[name];
copy = options[name];
if (target === copy) {
continue;
}
if (deep && copy && (_.isPlainObject(copy) || (copyIsArray = _.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && _.isArray(src) ? src : [];
} else {
clone = src && _.isPlainObject(src) ? src : {};
}
// WARNING: RECURSION
target[name] = _.extend(deep, clone, copy);
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
i++;
}
return target;
},
createElement: function(el, attr, html) {
var elem = document.createElement(el);
if (attr) {
for (var i in attr) {
elem.setAttribute(i, attr[i]);
}
}
if (html) {
elem.innerHTML = html;
}
return elem;
},
each: function(el, callback) {
if (el) {
var l = el.length;
while (l--) {
callback(el[l]);
}
}
},
on: function(parent, ev, target, callback, usecapture) {
if (usecapture === null) usecapture = false;
ev = ev.split(' ');
var l = ev.length,
glob = function(e) {
if (target === null) {
e._this = parent;
callback(e);
} else {
var par = _.matchUp(e.target, target, parent);
if (par) {
e._this = par;
callback(e);
}
}
};
while (l--) {
parent.addEventListener(ev[l], glob, usecapture);
}
},
remove: function(el) {
el.parentNode.removeChild(el);
},
createEvent: function(evName) {
var ev;
if (document.createEvent) {
ev = document.createEvent("HTMLEvents");
ev.initEvent(evName, true, true);
} else {
ev = document.createEventObject();
ev.eventType = evName;
}
ev.eventName = evName;
ev.memo = {};
return ev;
},
trigger: function(element, evName) {
var ev = _.createEvent(evName);
if (document.createEvent) {
element.dispatchEvent(ev);
} else {
element.fireEvent("on" + ev.eventType, ev);
}
},
clearSelection: function() {
if (window.getSelection) {
window.getSelection().removeAllRanges();
} else if (document.selection) {
document.selection.empty();
}
},
XHR: function(options) {
//$.ajax(options);
var def = {
request: false,
type: 'get',
dataType: 'json',
url: null,
data: null,
cache: true,
async: true,
contentType: true,
progress: null,
beforeSend: null,
error: null,
success: null,
complete: null
};
var xhr = _.extend({}, def, options),
datatype = (!(xhr.data)) ? 'undefined' :
(xhr.data instanceof FormData) ? 'formdata' :
(typeof xhr.data === 'string') ? 'string' :
'object';
formatURL = function(data) {
var url_split = xhr.url.split("?");
if (url_split.length !== 1) {
xhr.url += "&" + data;
} else {
xhr.url += "?" + data;
}
};
xhr.type = xhr.type.toUpperCase();
if (datatype == 'object') {
var param_count = 0,
name,
value,
tmp_data = xhr.data;
for (var param in tmp_data) {
if(tmp_data.hasOwnProperty(param)){
name = encodeURIComponent(param);
value = encodeURIComponent(tmp_data[param]);
if (param_count === 0) {
xhr.data = name + "=" + value;
} else {
xhr.data += "&" + name + "=" + value;
}
param_count++;
}
}
xhr.data = xhr.data;
}
if (xhr.data && typeof xhr.data == 'string' && xhr.type === "GET") {
formatURL(xhr.data);
}
if (!xhr.cache) {
formatURL(new Date().getTime());
}
if (_.hasXHR) {
// Modern non-IE
xhr.request = new XMLHttpRequest();
} else {
if (window.ActiveXObject) {
// Internet Explorer
xhr.request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
// No request object, break
return false;
}
}
xhr.request.onreadystatechange = function(e) {
if (xhr.request.readyState === 4 ) {
if (xhr.request.status == 200) {
if (xhr.success && _.isFunction(xhr.success)) {
var data = xhr.request.responseText;
// Returns responseText and request object
if (xhr.dataType == 'json') data = JSON.parse(data);
xhr.success(data, xhr.request.statusText);
}
} else {
if (xhr.error && _.isFunction(xhr.error)) {
// Returns request object
xhr.error(xhr.request, xhr.request.status, xhr.request.statusText);
}
}
if (xhr.complete && _.isFunction(xhr.complete)) {
xhr.complete(xhr.request);
}
}
};
xhr.request.upload.onprogress = function(e)
{
if (xhr.progress && _.isFunction(xhr.progress)) {
xhr.progress(e);
}
};
xhr.request.open(xhr.type, xhr.url, xhr.async);
if (xhr.contentType && xhr.type === "POST") {
xhr.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (xhr.beforeSend && _.isFunction(xhr.beforeSend)) {
if (xhr.beforeSend(xhr) === false) return xhr.request.abort();
}
xhr.request.send(xhr.data);
},
previewFiles: function(files, preview, max) {
var i = (files.length < max) ? files.length : max;
while (i--) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.createElement('img');
img.classList.add('preview');
img.file = file;
preview.appendChild(img);
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment