Tag Archive for js

jQuery dynamic loader – load jquery using pure js javascript if jQ is undefined or does not exist

// jQuery dynamic loader - load jQuery using pure javascript js
// if jQuery is undefined or does not exist, then load it

if ( !window.jQuery ) {
	var jqscript = document.createElement('script');
	jqscript.setAttribute("type", "text/javascript");
	jqscript.setAttribute("src", "<a href="http://code.jquery.com/jquery.min.js");" >http://code.jquery.com/jquery.min.js");</a>
	document.getElementsByTagName("head")[0].appendChild(jqscript);
};

source

javascript function within a function to repeat itself js jquery jq loop looping

// animation functions
		zlpFX = {
			show1: function() {
				$('div#mainBackground2').fadeOut(3000);
				$('div#transMoving').animate({
					paddingLeft: "180px",
					paddingTop: "20px"
				},
				4000).find('h3').fadeOut(2000);
				setTimeout("zlpFX.show2()", 14000);
			},
			show2: function() {
				$('div#mainBackground2').fadeIn(4000);
				$('div#transMoving').animate({
					paddingLeft: '220px',
					paddingTop: '75px'
				},
				4500).find('h3').fadeIn(6000);
				setTimeout("zlpFX.show1()", 14000);
			}
		};




		// now start the animation functions
		setTimeout("zlpFX.show1()", 11000);

source

MOOTOOLS JS – Clear input field onClick onFocus on click focus active

// 201004291250 - Mootools clear input on focus, return default value if no data entered
// FROM:  Clear text field with mootools on focus. - MooTools Users | Google Groups <a href="http://bit.ly/cHPev3" >http://bit.ly/cHPev3</a>

/* 
	I've got this snippet that will clear the value on focus and if the value of 
	the focus is '' it will put the default value again in the input. You will 
	need the default value to be on an attribute of the input, like alt or 
	anyother (if you don't bother about validation). 
	
	Fábio Miranda Costa 
	Engenheiro de Computação 
	<a href="http://meiocodigo.com" >http://meiocodigo.com</a> 

*/

// FUNCTION: 

Element.implement({ 
    clearFocusResetBlur: function(attr){ 
        var valueString = this.get(attr); 
        this.addEvents({ 
            'focus': function(){ 
                if( this.get('value') == valueString ) this.set('value',''); 
            }, 
            'blur': function(){ 
                if( this.get('value') == "" ) this.set('value',valueString); 
            } 
        }); 
    } 
}); 


// Usage
// HTML: 
// <input id="input_id" value="some value" alt="default value" /> 


// JS: 
$('.jform form .cleardefault').set('alt','value').clearFocusResetBlur('alt');

source

jsCookies – my simple easy pure js javascript cookies function

//  create my jsCookies function
var jsCookies = {

	// this gets a cookie and returns the cookies value, if no cookies it returns blank ""
	get: function(c_name) {
		if (document.cookie.length > 0) {
			var c_start = document.cookie.indexOf(c_name + "=");
			if (c_start != -1) {
				c_start = c_start + c_name.length + 1;
				var c_end = document.cookie.indexOf(";", c_start);
				if (c_end == -1) {
					c_end = document.cookie.length;
				}
				return unescape(document.cookie.substring(c_start, c_end));
			}
		}
		return "";
	},

	// this sets a cookie with your given ("cookie name", "cookie value", "good for x days")
	set: function(c_name, value, expiredays) {
		var exdate = new Date();
		exdate.setDate(exdate.getDate() + expiredays);
		document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toUTCString());
	},

	// this checks to see if a cookie exists, then returns true or false
	check: function(c_name) {
		c_name = jsCookies.get(c_name);
		if (c_name != null && c_name != "") {
			return true;
		} else {
			return false;
		}
	}

};
// end my jsCookies function

// USAGE - get    ::   jsCookies.get("cookie_name_here");  [returns the value of the cookie]
// USAGE - set    ::   jsCookies.set("cookie_name", "cookie_value", 5 );  [give name, val and # of days til expiration]
// USAGE - check  ::   jsCookies.check("cookie_name_here");  [returns only true or false if the cookie exists or not]

source

js jQueryLoader – check if $ is undefined, then load jquery with pure javascript if needed

/* I used to use (!$) or ($ == undefined) but that doesn't work sucka! */

if (!window.jQuery) {
	var jqscript = document.createElement('script');
	jqscript.setAttribute("type", "text/javascript");
	jqscript.setAttribute("src", "<a href="http://code.jquery.com/jquery.min.js");" >http://code.jquery.com/jquery.min.js");</a>
	document.getElementsByTagName("head")[0].appendChild(jqscript);
};

source

SimpleSelector, Javascript DOM selector

/*!
 * $imple$elector
 *
 * Selector by id, className or tagName, f.e.:
 * $$( '#wrap' ) or $$( '.special' ) or $$( 'p' )
 *
 * Mulitple selectors seperated by comma, f.e.:
 * $$( '#id, .cls' )
 *
 * Give context as second param, f.e.:
 * $$( 'a', '#wrap' ) or $$( 'a', wrapNode ) or $$( 'a', [node1, node2] )
 *
 * @version   0.2
 * @author    Victor Villaverde Laan
 * @link      <a href="http://www.freelancephp.net/simpleselector-javascript-dom-selector/" >http://www.freelancephp.net/simpleselector-javascript-dom-selector/</a>
 * @license   MIT license
 */
var SimpleSelector = {

	/**
	 * Find elements with the given selector within the context
	 * @param selector [string]
	 * @param context  [string | DOM node | array of DOM nodes]
	 * @return [DOM node | array of DOM nodes | empty array]
	 */
	find: function ( selector, context ) {
		var selectors = selector.split( ',' ),
			elements = [],
			wrappers = [];

		// set wrappers
		if ( typeof context == 'string' ) {
			var wraps = SimpleSelector.find( context );
			// set array to wrappers
			wrappers = ( wraps.constructor == Array ) ? wraps : [ wraps ];
		} else if ( context && context.constructor == Array ) {
			wrappers = context;
		} else {
			// document is default context
			wrappers.push( context || document );
		}

		// find matching elements within the wrappers (context)
		for ( var a = 0, b = wrappers.length; a < b; a++ ) {
			for ( var x = 0, y = selectors.length; x < y; x++ ) {
				// selector: trim spaces
				var s = selectors[x].replace( / /g, '' ),
					// get operator
					operator = s.substr( 0, 1 ),
					// get key
					key = s.substr( 1 ),
					els = [];

				// get matching elements
				if ( operator == '#' ) {
					// get element by id
					els[0] = document.getElementById( key );
					// check if element is part of context
					if ( els[0] && SimpleSelector.isDescendant( els[0], wrappers[ a ] ) )
						elements.push( els[0] );
				} else if ( operator == '.' ) {
					// get element by className
					els = SimpleSelector.getByClass( key, wrappers[ a ] );
					// convert type to array
					els = [].slice.call( els, 0 );
					// add to elements collection
					elements = elements.concat( els );
				} else {
					// get element by tagName
					els = wrappers[ a ].getElementsByTagName( s );
					// add to elements collection
					// in this case [].slice.call( els, 0 ) does not work
					// in IE, says constructor is undefined??
					for ( var i = 0, j = els.length; i < j; i++ )
						elements.push( els[ i ] );
				}
			}
		}

		// return single element or array of elements
		return ( elements.length == 1 ) ? elements[0] : elements;
	},

	/**
	 * Check wether an element is a descendant of the given ancestor
	 * @param descendant [DOM node]
	 * @param ancestor   [DOM node]
	 * @return [boolean]
	 */
	isDescendant: function ( descendant, ancestor ) {
		return ( ( descendant.parentNode == ancestor )
					|| ( descendant.parentNode != document )
				&& arguments.callee( descendant.parentNode, ancestor ) );
	},

	/**
	 * Cross browser function for getting elements by className
	 * @param className [string]
	 * @param context   [DOM node]
	 * @return [array of DOM nodes]
	 */
	getByClass: function ( className, context ) {
		var elements = [],
			expr = new RegExp('b' + className + 'b'),
			wrapper = context || document,
			allElements = wrapper.getElementsByTagName( '*' );

		// filter all elements that contain the given className
		for ( var x = 0, y = allElements.length; x < y; x++ ) {
			if ( expr.test( allElements[ x ].className ) )
				elements.push( allElements[ x ] );
		}

		return elements;
	}

};

// if global $$ is not set
if ( ! window.$$ )
	window.$$ = SimpleSelector.find;

source

Strip Tags

String.prototype.strip_tags = function() { 
    return this.replace(/<(.|
)*?>/g, ''); 
}

source

Sort Objects by Date Property

Array.prototype.sortByDate = function(sortOrder) {
	var objArray = this;    // [Obj, Obj, Obj] where each Obj 
                                // has prop: "sortDate" with val: "YYYY-MM-DD"
	
	var sBD = function(a, b) {
		var dateStringA = a.sortDate.split("-");
		var dateStringB = b.sortDate.split("-");
		var dateA = new Date(dateStringA[0], dateStringA[1], dateStringA[2]);
		var dateB = new Date(dateStringB[0], dateStringB[1], dateStringB[2]);
		return dateA - dateB;
	};

	if (sortOrder == "desc") {
		objArray.sort(sBD).reverse();
	} else if (sortOrder == "asc") {
		objArray.sort(sBD);
	} else if (!sortOrder) {
		objArray.sort(sBD);
	}
}

source

Range module – SoQ 3.1.0

$(function(){
	$.e.range = function(a1,a2,a3){
		var a1=$(a1), p1=this.positionFromEdge(), p2=a1.positionFromEdge(), r=[];
		
		for(var y=0,T=this,Y=T.length;y<Y;y++){
			for(var z=0,Z=a1.length;z<Z;z++){
				var AI = { x:a1[z].offsetWidth+a1[z].offsetLeft, y:a1[z].offsetHeight+a1[z].offsetTop };
				var TI = { end:{ x:T[y].offsetWidth+T[y].offsetLeft, y:T[y].offsetHeight+T[y].offsetTop }, start : { x:T[y].offsetLeft, y:T[y].offsetTop } };
				
				if((a1[z].offsetLeft).range(TI.start.x, TI.end.x) && (a1[z].offsetTop).range(TI.start.y, TI.end.y) || (AI.x).range(TI.start.x, TI.end.x) && (AI.y).range(TI.start.y, TI.end.y)){
					$.func(a2).call(this, a1[z]);
				} else {
					$.func(a3).call(this, a1[z]);
				}
			}
		}
		
		return this;
	};
	

	// ========= Example
	$(".b1").range(".b2, .b3, .b4", function(a1){
		$(a1).css("background-color:green;");
	}, function(a1){
		$(a1).css("background-color:red;");
	});
});

source

Javascript OOP Example (Constructor Version)

/*
	Author: Alvin Crespo
	Topic: OOP in Javascript
	Reference: Javascript "The Definitive Reference" by David Flanagan
	
	NOTES:
		* Javascript does not support TRUE classes like Java, C++ and C# do.
		* It is possible to define pseudoclasses in Javascript.
		
	A Constructor Method:
		new Object ()
	
	Object from Constructors:
		var array = new Array(12);
		var today = new Date();
	
		* NEW operator must be followed by the invocation of a function
		* Function that is designed to be used with the NEW operator is called a constructor
		* Purpose of the constructor is to initialize a new object
*/

	//Constructor Method
	//*************************************************************************
	//Define the constructor
	function Square(objectW,objectH){
	
		//initializes by using the keyword THIS
		this.width = objectW;
		this.height = objectH;
		
		//this is how to add a method to a constructor
		this.area = function(){ console.log("Area as a property/function of Square: " + (this.width * this.height)); } 
		//The above area function works but is not optimal, because each Square will the area as a property
		
		//no return statement
	}
	
	//Invoking the constructor to create Square objects
	//square1 = {width:2, height:4}
	var square1 = new Square(5,10); 
	//calling a constructors method
	var sqArea1 = square1.area();
	
	/*
		About Prototype Object
		----------------------------
		
		* Every javascript object includes an internal reference to 
			another object, known as a prototype object
	*/
	
	//creating a prototype
	Square.prototype.LargerSide = function(){
		var result = '';
		//inheritance is automatic as part of the process of looking up a property value, thus
		//	width and height can be used
		if(this.width > this.height){
			result = "Width is Larger";
		}else if(this.width == this.height){		
			result = "Width and Height are the same";
		}else{
			result = "Height is Larger";		
		}
		
		console.log("Area as a prototype/function of Square: " + result);
	}//end of LargerSide prototype for Square
	
	square1.LargerSide();
	//*************************************************************************

source