Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Forked from rmanalan/$w.js
Created November 2, 2011 18:03
Show Gist options
  • Save xeoncross/1334388 to your computer and use it in GitHub Desktop.
Save xeoncross/1334388 to your computer and use it in GitHub Desktop.
Illustration of a jQuery like object
var $w = function(){
var $w = function(){
return new $w.init;
}
$w.prototype = {
// add all of the methods/props you want accessible as $w().method() or $w().prop here:
init: function(){
console.log('init called');
},
length: 0
}
$.extend($w,{
// add all of the methods/props you want accessible as $w.method() or $w.prop here:
sayHello: function(){
console.log('hello');
}
})
return $w;
}();
/*!
* jLim Core
*
* jLim is a small JavaScript base code. It can be used to built your own
* JavaScript library or framework.
*
* @version 0.1.2
* @author Victor Villaverde Laan
* @link http://www.freelancephp.net/jlim-small-javascript-framework/
* @license MIT license
*/
(function ( window ) {
/**
* jLim function
* @param {string|DOM node|array of DOM nodes} selector When selector is not a string the context will be ignored
* @param {string|DOM node|array of DOM nodes} context
* @return {jLim} New instance
*/
var jLim = window.jLim = function ( selector, context ) {
return new jLim.core.init( selector, context );
};
// set $ global ( when not already exists )
if ( ! window.$ )
window.$ = jLim;
/**
* jLim Core
*/
jLim.core = jLim.prototype = {
els: [],
selector: [],
context: [],
/**
* Init function, set selected elements
* @param {string|DOM node|array of DOM nodes} selector When selector is not a string the context will be ignored
* @param {string|DOM node|array of DOM nodes} context Optional, default is document
*/
init: function ( selector, context ) {
// set selector and context property
this.selector = selector || document;
this.context = context || document;
// get elements by selector
if ( typeof selector == 'string' ) {
// trim spaces at the begin and end
selector = jLim.trim( selector );
if ( selector == 'body' ) {
// set body
this.els = document.body;
} else if ( selector.substr( 0, 1 ) == '<' ) {
// create element
this.els = jLim.create( selector );
} else {
// find elements
this.els = jLim.selector( selector, context );
}
} else if ( jLim.isFunction( selector ) ) {
// set DOM ready function
jLim.ready( selector );
} else if ( selector instanceof jLim ) {
this.els = selector.get();
} else {
this.els = selector;
}
// make sure elements property is an array
if ( ! jLim.isArray( this.els ) )
this.els = this.els ? [ this.els ] : [];
// support for using jLim object as an array
// set indices
for ( var i in this.els )
this[ i ] = this.els[ i ];
// set length property
this.length = this.els.length;
},
/**
* Get element (return all current elements when no index given)
* @param {integer} index
* @return {DOM node|array of DOM nodes}
*/
get: function ( index ) {
if ( typeof index == 'undefined' )
return this.els;
var el = ( index === -1 )
? this.els.slice( index )
: this.els.slice( index, +index + 1 );
return el.length ? el[0] : null;
},
/**
* Get count of current elements
* @return {integer}
*/
size: function () {
return this.els.length;
},
/**
* Call function for each element
* @param {function} fn
* @param {array} args
* @return {this} For chaining
*/
each: function ( fn, args ) {
jLim.each( this.els, fn, args );
return this;
},
/**
* Find elements within the current elements (context)
* @param {string} selector
* @return {jLim} Instance of new selection
*/
find: function ( selector ) {
return this.chain( selector, this.els );
},
/**
* Add to the current elements in a new created jLim object
* @param {string|DOM node|array of DOM nodes} selector When selector is not a string the context will be ignored
* @param {string|DOM node|array of DOM nodes} context Optional, when none is given it will use the context of current jLim object
* @return {jLim} Instance of new selection
*/
add: function ( selector, context ) {
var $new = this.chain( selector, context || this.context ),
els = this.els.concat( $new.get() );
$new.els = els;
return $new;
},
/**
* Set one of current elements as new jLim object
* @param {integer} index Negative integer also possible, -1 means last item
* @return {jLim} Instance of new selection
*/
eq: function ( index ) {
return this.chain( this.get( index ) );
},
/**
* Set slice of current elements as new jLim object
* @param {integer} start Like the first param of the standard Array.slice() function
* @param {integer} end Like the second param of the standard Array.slice() function
* @return {jLim} Instance of new selection
*/
slice: function ( start, end ) {
var els = this.els.slice( start, end || this.els.length );
return this.chain( els );
},
/**
* Chain content as new jLim object
* @param {string|DOM node|array of DOM nodes} selector When selector is not a string the context will be ignored
* @param {string|DOM node|array of DOM nodes} context Optional
* @return {jLim} Instance of new selection
*/
$: function ( selector, context ) {
var $new = jLim( selector, context );
$new.prevjLim = this;
return $new;
},
/**
* Set pointer to previous jLim object
* @return {jLim} Previous jLim object in the chain
*/
end: function () {
return this.prevjLim || jLim( null );
}
};
// deprecated chain() method replaced by $
jLim.core.chain = jLim.core.$;
// init function gets core prototype
jLim.core.init.prototype = jLim.core;
/**
* Extend method
* @return {jLim|jLim.core|object|array|boolean}
*/
jLim.extend = jLim.core.extend = function () {
// target is current object if only one argument
var i = 0,
target = this,
deep = false,
obj, empty, item, x;
// check extending recursive (deep)
if ( typeof arguments[ 0 ] === 'boolean' ) {
deep = true;
i = 1;
if ( arguments.length > 2 ) {
i = 2;
target = arguments[ 1 ];
}
} else if ( arguments.length > 1 ) {
i = 1;
target = arguments[ 0 ];
}
// loop through all source objects
for ( x = i; x < arguments.length; x++ ) {
obj = arguments[ x ];
// copy object items (properties and methods)
for ( item in obj ) {
if ( obj[ item ] === target )
continue;
if ( deep && typeof obj[ item ] == 'object' && obj[ item ] !== null ) {
// item is also object, make copy
empty = jLim.isArray( obj[ item ] ) ? [] : {};
target[ item ] = jLim.extend( deep, target[ item ] || empty, obj[ item ] );
} else {
// copy property or method
target[ item ] = obj[ item ];
}
}
}
// return modified target
return target;
};
/**
* Extent basic functions
*/
jLim.extend({
/**
* Selector method
* @param {string} selector
* @param {string|DOM node|array of DOM nodes} context Default document
* @return {DOM node|array of DOM nodes|empty array}
*/
selector: function ( selector, context ) {
return jLim.$$( selector, context );
},
/**
* Add DOMReady callbacks
* @param {function|string} fn When string will be run like code with eval()
* @return {this}
*/
ready: function ( fn ) {
// default use the DOMReady add() method
jLim.DOMReady.add( fn );
// return this for chaining
return this;
},
/**
* Create DOM element
* @param {string} html
* @return {DOM element|array of DOM elements}
*/
create: function ( html ) {
var ph = document.createElement( 'div' ),
els = [];
ph.innerHTML = html;
// get created elements
els = ph.childNodes;
// return element or array of elements
return els.length == 1 ? els[0] : els;
},
/**
* Each function for arrays and objects
* @param {object|array} obj
* @param {function} fn
* @return {this}
*/
each: function ( obj, fn ) {
var item, retVal;
// call given function for each item
for ( item in obj ) {
retVal = fn.call( obj[ item ], item, obj[ item ] );
// do not continue further when return value is false
if ( retVal === false )
break;
}
// return this for chaining
return this;
},
/**
* Trim spaces
* @param {string} str
* @return {string}
*/
trim: function ( str ) {
return str.replace( /^\s+/, '' ).replace( /\s+$/, '' );
},
/**
* Check if argument is array
* @param {mixed} obj
* @return {boolean}
*/
isArray: function ( obj ) {
return ( Object.prototype.toString.call( obj ) === "[object Array]" );
},
/**
* Check if argument is function
* @param {mixed} obj
* @return {boolean}
*/
isFunction: function ( obj ) {
return ( Object.prototype.toString.call( obj ) === "[object Function]" );
}
});
/**
* External components
*/
/**
* DOMReady
*
* @version 1.0
* @link http://www.freelancephp.net/domready-javascript-object-cross-browser/
* @license MIT license
*/
jLim.DOMReady=(function(){var fns=[],isReady=false,errorHandler=null,getFunc=function(fn){if(typeof fn=='string')return function(){eval(fn);};return fn;},ready=function(){isReady=true;for(var x=0;x<fns.length;x++){try{fns[x]();}catch(err){if(errorHandler)errorHandler(err);}}};this.setOnError=function(fn){errorHandler=getFunc(fn);return this;};this.add=function(fn){fn=getFunc(fn);if(isReady){fn();}else{fns[fns.length]=fn;}return this;};if(window.addEventListener){document.addEventListener('DOMContentLoaded',function(){ready();},false);}else{(function(){if(!document.uniqueID&&document.expando)return;var tempNode=document.createElement('document:ready');try{tempNode.doScroll('left');ready();}catch(err){setTimeout(arguments.callee,0);}})();}return this;})();
/**
* SS
*
* @version 0.1.1
* @link http://www.freelancephp.net/simple-css-selector-function/
* @license MIT license
*/
var $$=function(selector,context){var isObjType=function(o,type){return Object.prototype.toString.call(o)==='[object '+type+']';},isDesc=function(d,a){return d.parentNode==a||d.tagName.toUpperCase()!='HTML'&&isDesc(d.parentNode,a);},s=selector,c=context,els=[];s=s.split(',');c=isObjType(c,'String')?$$(c):c&&c.length?c:document;if(!isObjType(c,'Array'))c=[c];for(var i in c){for(var j in s){var strim=s[j].replace(/\s+/g,''),sp=s[j].split(' '),op=strim.substr(0,1),name=strim.substr(1),tels=[],nextContext;if(sp.length>1){nextContext=$$(sp[0],c[i]);tels=$$(sp.slice(1).join(' '),nextContext);els=els.concat(tels);}else if(op=='#'){tels[0]=c[i].getElementById?c[i].getElementById(name):document.getElementById(name);if(tels[0]&&isDesc(tels[0],c[i]))els.push(tels[0]);}else if(op=='.'){var expr=new RegExp('(^|\\s)'+name+'(\\s|$)'),all=c[i].getElementsByTagName('*');for(var v=0,w=all.length;v<w;v++){if(expr.test(all[v].className))els.push(all[v]);}}else{tels=c[i].getElementsByTagName(strim);for(var y=0,z=tels.length;y<z;y++)els.push(tels[y]);}}}return els.length==1?els[0]:els;};
jLim.$$=$$;
})( window );
(function () {
/**
* Light
*
* This is an extreme small and easy JavaScript library. It can
* be used for small websites which won't be needing all the
* functionality of the bigger libraries around. Or use it to
* learn how to create your own library or framework.
*
* @author Victor Villaverde Laan <info@freelancephp.net>
* @link http://www.freelancephp.net/light-4kb-min-jquery-light/
* @license MIT license
*/
/**
* Light function
*/
window.Light = function ( selector, parent ) {
return new Light.core.init( selector, parent );
};
// if global $ is not set
if ( ! window.$ )
window.$ = window.Light;
/**
* Light.core
* Contains the core functions
*/
Light.core = Light.prototype = {
// init function, set selected elements
init: function ( selector, parent ) {
var els;
selector = selector || window; // default is window
parent = parent || document; // default is document
els = ( typeof selector == 'string' )
? Light.selector( selector, parent ) // use selector method
: els = selector;
// reset elements
this.els = [];
if ( typeof els.length != 'undefined' ) {
// els is an array or object
for (var i = 0, max = els.length; i < max; i++)
this.els.push(els[i]);
} else {
// els is an element
this.els.push( els );
}
return this;
},
// get the element of given index (return all elements when no index given)
get: function ( index ) {
return ( typeof index == 'undefined' )
? this.els
: this.els[index];
},
// get number of selected elements
count: function () {
return this.els.length;
},
// set function to be run for each selected element
each: function ( fn ) {
for ( var x = 0, max = this.els.length; x < max; x++ )
fn.call( this, this.els[x] );
return this;
},
// set attribute value
attr: function ( name, value, type ) {
this.each(function( el ) {
if ( typeof type == 'undefined' ) {
el[name] = value;
} else {
el[type][name] = value;
}
});
return this;
},
// set styles
css: function ( styles ) {
var that = this;
this.each(function( el ) {
for ( var name in styles )
that.attr( name, styles[name], 'style' );
});
return this;
},
// add given className
addClass: function ( className ) {
this.each(function ( el ) {
el.className += ' ' + className;
});
return this;
},
// remove given className
removeClass: function ( className ) {
this.each(function ( el ) {
el.className = el.className.replace( className, '' );
});
return this;
},
// add event action
on: function ( event, fn ) {
var addEvent = function( el ) {
if ( window.addEventListener ) {
el.addEventListener( event, fn, false );
} else if ( window.attachEvent ) {
el.attachEvent( 'on'+ event, function() {
fn.call( el, window.event );
});
}
};
this.each(function( el ) {
addEvent( el );
});
return this;
},
// add function to be executed when the DOM is ready
ready: function ( fn ) {
DOMReady.add( fn );
return this;
},
// remove selected elements from the DOM
remove: function () {
this.each(function( el ) {
el.parentNode.removeChild( el );
});
return this;
}
};
// Selector, default support:
// $('#id') - get element by id
// $('.className') - get element(s) by class-name
// $('tagName') - get element(s) by tag-name
Light.selector = function ( selector, context ) {
var sels = selector.split( ',' ),
el, op, s;
for ( var x = 0; x < sels.length; x++ ) {
// trim spaces
var sel = sels[x].replace(/ /g, '');
if ( typeof sel == 'string' ) {
op = sel.substr( 0, 1 ); // operator
s = sel.substr( 1 ); // name without operator
if ( op == '#' ) {
el = document.getElementById( s );
el = ( isDescendant( el, context ) ) ? el : null;
} else if ( op == '.' ) {
el = getElementsByClassName(s, context);
} else {
el = context.getElementsByTagName(sel);
}
}
}
return el;
};
// init gets core prototype
Light.core.init.prototype = Light.core;
/**
* Helpers
*/
// DOMReady, add functions to be executed when the DOM is ready
var DOMReady = (function () {
var fns = [],
isReady = false,
ready = function () {
isReady = true;
// call all functions
for ( var x = 0; x < fns.length; x++ )
fns[x].call();
};
// public add method
this.add = function ( fn ) {
// eval string in a function
if ( fn.constructor == String ) {
var strFunc = fn;
fn = function () { eval( strFunc ); };
}
// call imediately when DOM is already ready
if ( isReady ) {
fn.call();
} else {
// add to the list
fns[fns.length] = fn;
}
};
// For all browsers except IE
if ( window.addEventListener )
document.addEventListener( 'DOMContentLoaded', function(){ ready(); }, false );
// For IE
// Code taken from http://ajaxian.com/archives/iecontentloaded-yet-another-domcontentloaded
(function(){
// check IE's proprietary DOM members
if ( ! document.uniqueID && document.expando ) return;
// you can create any tagName, even customTag like <document :ready />
var tempNode = document.createElement('document:ready');
try {
// see if it throws errors until after ondocumentready
tempNode.doScroll('left');
// call ready
ready();
} catch ( err ) {
setTimeout(arguments.callee, 0);
}
})();
return this;
})();
// create a static reference
Light.ready = DOMReady.add;
// Check wether an element is a descendant of the given ancestor
function isDescendant( desc, anc ){
return ( ( desc.parentNode == anc ) || ( desc.parentNode != document ) && isDescendant( desc.parentNode, anc ) );
};
// Cross browser function for getting elements by className
function getElementsByClassName( className, parent ) {
var a = [],
re = new RegExp('\\b' + className + '\\b'),
els = parent.getElementsByTagName( '*' );
parent = parent || document.getElementsByTagName( 'body' )[0];
for ( var i = 0, j = els.length; i < j; i++ )
if ( re.test( els[i].className ) )
a.push( els[i] );
return a;
};
})();
// https://gist.github.com/1084136
(function(window, undefined) {
var MyObj = (function () {
var MyObj = function () {
return new MyObj.fn.init();
};
MyObj.fn = MyObj.prototype = {
init : function () {
return this;
},
count : function () {
for(var i in this) {
if (this.hasOwnProperty(i)) {
console.log("Element "+i+" is "+this[i]);
}
}
}
};
MyObj.fn.init.prototype = MyObj.fn;
MyObj.test = 'yay';
return MyObj;
}());
window.MyObj = MyObj;
}(window));
// http://blog.buymeasoda.com/creating-a-jquery-like-chaining-api
var myQuery, $;
(function() {
myQuery = $ = function(selector) {
return new MyQuery(selector);
};
var MyQuery = function(selector) {
// Lets make a really simplistic selector implementation for demo purposes
var nodes = document.getElementsByTagName(selector);
for (var i = 0; i < nodes.length; i++) {
this[i] = nodes[i];
}
this.length = nodes.length;
return this;
};
// Expose the prototype object via myQuery.fn so methods can be added later
myQuery.fn = MyQuery.prototype = {
// API Methods
hide: function() {
for (var i = 0; i < this.length; i++) {
this[i].style.display = 'none';
}
return this;
},
remove: function() {
for (var i = 0; i < this.length; i++) {
this[i].parentNode.removeChild(this[i]);
}
return this;
}
// More methods here, each using 'return this', to enable chaining
};
}());
// Example usage
$('p').hide().remove();
// Add a plugin
$.fn.red = function() {
for (var i = 0; i < this.length; i++) {
this[i].style.color = 'red';
}
return this;
}
$('li').red();
/**
* Small library to test a jQuery like interface.
* Based on jQuery, vX, moo.fx, and others.
*
* David <xeoncross.com>
* MIT License
*/
(function(window, undefined)
{
var myQuery = function(selector, context)
{
return new myQuery.fn.init(selector, context);
};
// Expose the prototype object via myQuery.fn so methods can be added later
myQuery.fn = myQuery.prototype = {
// ---- Core -----
init: function(selector, context)
{
// Allow searching for DOM children of a certain node
if( ! context) context = window.document;
if( ! selector) return this;
var nodes = [];
if(typeof selector == 'object')
{
nodes[0] = selector;
}
else if(selector.charAt(0) === "#")
{
nodes[0] = context.getElementById(selector.substring(1));
}
else if(selector.charAt(0) === ".")
{
nodes = this.getElementsByClass(selector.substring(1), context);
}
else
{
// Lets make a really simplistic selector implementation for demo purposes
nodes = context.getElementsByTagName(selector);
}
for (var i = 0; i < nodes.length; i++)
{
this[i] = nodes[i];
}
this.length = nodes.length;
return this;
},
// Call the given function after the DOM content is loaded
ready: function(callback)
{
if("\v" == "v")
{
setTimeout(callback, 0); // IE
}
else
{
$(document).on('DOMContentLoaded', callback);
}
},
// Fix an event object
fixEvent: function(event)
{
if ( ! event) var event = window.event;
// Fix target property, if necessary (IE 6/7/8 & Safari2)
if ( ! event.target)
{
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (Safari)
if (event.target.nodeType === 3)
{
event.target = event.target.parentNode;
}
event.posx = 0;
event.posy = 0;
if (event.pageX || event.pageY)
{
event.posx = event.pageX;
event.posy = event.pageY;
}
else if (event.clientX || event.clientY)
{
event.posx = event.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
event.posy = event.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
return event;
},
// Stop the default event action
stop: function(event)
{
event.preventDefault ? event.preventDefault() : event.returnValue = false;
},
// Get elements by class name
getElementsByClass: function(name, context, tag)
{
var elements = [],
nodes = context.getElementsByTagName(tag ? tag : '*'),
length = nodes.length;
for(k=length;k--;)
{
if(nodes[k].className.split(" ").indexOf(name) > -1)
{
elements.push(nodes[k]);
}
}
return elements;
},
// Get selected text
selection: function()
{
var e = window.getSelection,
k=document.getSelection,
x=document.selection;
return (e ? e() : (k) ? k() : (x ? x.createRange().text : 0));
},
// URL encode an object
uriEncode:function(object)
{
var uri = '';
for(var x in object)
{
uri += '&' + x + '=' + encodeURIComponent(object[x]);
}
return uri.slice(1);
},
// Decode a JSON string
jsonDecode:function(string)
{
return JSON ? JSON.parse(string) : eval('(' + string + ')');
},
// ----- FX Methods ----
// Caculate the ease value
ease: function(value)
{
return (1-Math.cos(value * Math.PI))/2;
},
// Frames, Interval, Callback, FinishCallback
fx: function(v,n,c,f,u,y)
{
u = 0;
(y = function()
{
u++ < v && c($(this).ease(u/v)) !== 0 ? setTimeout(y,n) : (f ? f() : 0)
//u++ < v && c(u/v) !== 0 ? setTimeout(y,n) : (f ? f() : 0)
})();
},
// Direction in/out, Finish Callback, Frames, Interval
fade:function(direction, callback, frames, interval)
{
d = direction == 'in';
if( ! frames) frames = 15;
if( ! interval) interval = 50;
for (i = 0; i < this.length; ++i)
{
(function(item, d)
{
$(this).fx(frames, interval, function(a)
{
a = (d ? 0 : 1) + ( d ? 1 : -1) * a;
item.style.opacity = a;
item.style.filter = 'alpha(opacity='+100*a+')';
}, callback);
})(this[i], d);
}
return this;
},
// X-Offset, Y-Offset
move: function(x,y)
{
for (i = 0; i < this.length; ++i)
{
this[i].style.left = parseInt(this[i].style.left) + x + "px";
this[i].style.top = parseInt(this[i].style.top) + y + "px";
}
},
// Direction, Element, Finish Callback, Frames, Interval
slide: function(direction, callback, frames, interval, q)
{
d = direction == 'in';
if( ! frames) frames = 30;
if( ! interval) interval = 20;
for (i = 0; i < this.length; ++i)
{
(function(item, d, callback, q)
{
if(d)
{
item.style.height = '';
item.style.display = '';
}
if( ! q) q = $().position(item).h;
$().fx(
frames,
interval,
function(a)
{
//a = $.fn.ease((d ? 0 : 1) + (d ? 1 : -1) * a);
a = (d ? 0 : 1) + (d ? 1 : -1) * a;
item.style.height = (a*q) + 'px';
},function()
{
if( ! d ) item.style.display = 'none';
if(callback) callback();
}
);
})(this[i], d, callback, q);
}
return this;
},
// Hide the elements
hide: function()
{
for (var i = 0; i < this.length; i++)
{
this[i].style.display = 'none';
}
return this;
},
// Show the elements
show: function()
{
for (var i = 0; i < this.length; i++)
{
this[i].style.display = '';
}
return this;
},
// ----- API Methods ----
// For each element matched by selector
each: function(callback, args)
{
var length = this.length;
for (i = 0; i < length; ++i)
{
if (callback.call(this[i], i, args) === false) break;
}
return this;
},
// Add an event callback
on: function(type, callback, capturing)
{
var length = this.length;
for (i = 0; i < length; ++i)
{
var item = this[i];
//console.log(item);
if(item.attachEvent || item.addEventListener(type, callback, capturing ? true : false))
{
item['e'+type+callback] = callback;
item[type+callback] = function()
{
item['e'+type+callback].call(event.srcElement, event);
};
item.attachEvent('on'+type,item[type+callback]);
}
}
return this;
},
// Remove an event callback
un: function(type, callback)
{
var length = this.length;
for (i = 0; i < length; ++i)
{
var item = this[i];
//console.log(item);
if( ! callback)
{
console.log('Cannot remove Handler!');
item['on'+type] = null;
//item.removeAttribute('on'+type);
}
item.attachEvent
? item.detachEvent('on'+type,item[type+callback])
: item.removeEventListener(type,callback,0);
}
return this;
},
// Fire an event callback
fire: function(type, bubbling)
{
var length = this.length;
for (i = 0; i < length; ++i)
{
var item = this[i];
//console.log(item);
if (item.fireEvent)
{
item.fireEvent('on' + type)
}
else
{
var event = document.createEvent('Events');
// type, bubbling, cancelable
event.initEvent(type, (bubbling ? bubbling : true), true);
item.dispatchEvent(event);
}
}
return this;
},
// Insert the current node after the given node
insertAfter: function(node)
{
for (var i = 0; i < this.length; i++)
{
node.parentNode.insertBefore(this[i], node.nextSibling);
}
return this;
},
// Get the attributes
attr: function(name, value)
{
var values = [];
for (var i = 0; i < this.length; i++)
{
if(value === undefined)
{
values[i] = this[i].getAttribute(name);
}
else
{
this[i].setAttribute(name, value);
}
}
return values;
},
// Get the CSS styles
css: function(name, value)
{
name = name.replace(/-(.)/,function(all, match){return match.toUpperCase()});
if(val===_undefined)
return [item.style[name]];
item.style[name] = val;
},
// Remove the elements
remove: function()
{
for (var i = 0; i < this.length; i++)
{
this[i].parentNode.removeChild(this[i]);
}
return this;
},
// Position of an object
position: function(e)
{
var a = {
l:0,
t:0,
w:e.offsetWidth,
h:e.offsetHeight
};
do
{
a.l+=e.offsetLeft;
a.t+=e.offsetTop
}
while(e = e.offsetParent);
return a;
},
// Have that class?
hasClassName: function(className)
{
for (var i = 0; i < this.length; i++)
{
if( ! this[i].className.match(new RegExp("\\b"+className+"\\b")))
{
return false;
}
}
return true;
},
// Add a class
addClassName: function(className)
{
for (var i = 0; i < this.length; i++)
{
if ( ! $(this[i]).hasClassName(className))
{
this[i].className += ' ' + className;
}
}
return this;
},
// Remove class
removeClassName: function(className)
{
for (var i = 0; i < this.length; i++)
{
if ($(this[i]).hasClassName(className))
{
this[i].className = this[i].className.replace(className, '');
}
}
return this;
},
// -------- AJAX ----------
// URL, Finish Callback, POST data
ajax: function(url, callback, post)
{
var x = new (window.XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP');
x.open(post ? 'POST' : 'GET', url, 1);
x.setRequestHeader('X-Requested-With','XMLHttpRequest');
post && x.setRequestHeader('Content-type','application/x-www-form-urlencoded');
x.onreadystatechange = function()
{
x.readyState > 3 && callback && callback(x.responseText, x);
};
x.send(post);
return x;
},
// Form, AJAX Callback
ajaxForm:function(callback)
{
for (var i = 0; i < this.length; i++)
{
(function(form, callback)
{
//console.log(form, this);
$(form).on('submit', function(event)
{
// Prevent default action
$(this).stop(event);
// Collect form data
var data = $(form).serialize(form);
// Prevent response caching (IE)
var url = form.action + (form.action.indexOf('?') < 0 ? '?' : '&') + '_ts=' + (+ new Date);
// Submit
$(form).ajax(url, callback, data);
});
})(this[i], callback);
}
return this;
},
// Convert the given form values into an object
serialize: function(form)
{
function g(n)
{
return form.getElementsByTagName(n);
};
function nv(e)
{
if(e.name) return encodeURIComponent(e.name) + '=' + encodeURIComponent(e.value);
};
var i = this.collect(
g('input'),
function(i)
{
if((i.type != 'radio' && i.type != 'checkbox') || i.checked)
{
return nv(i);
}
}
);
var s = this.collect(g('select'), nv);
var t = this.collect(g('textarea'), nv);
return i.concat(s).concat(t).join('&');
},
// Build the array of form values
collect:function(a, func)
{
var n=[];
for(var i = 0; i < a.length; i++)
{
var v = func(a[i]);
if(v != null) n.push(v);
}
return n;
}
}
myQuery.fn.init.prototype = myQuery.fn;
window.myQuery = window.$ = myQuery;
})(window);
/*
$().ready(function()
{
var callback = function(){ console.log(this); };
$('a').on('click', callback);
$('a').fire('click');
$('a').un('click', callback);
$('li').fade('out', function()
{
$('li').fade('in');
});
});
*/
var $w = function(){
var $w = function(){
return new $w.init;
}
$w.prototype = {
// add all of the methods/props you want accessible as $w().method() or $w().prop here:
init: function(){
console.log('init called');
},
length: 0
}
$.extend($w,{
// add all of the methods/props you want accessible as $w.method() or $w.prop here:
sayHello: function(){
console.log('hello');
}
})
return $w;
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment