Tag Archive for javascript

Javascript w3c validator

javascript:void(document.location='<a href="http://validator.w3.org/check?" >http://validator.w3.org/check?</a>
charset=%28detect+automatically%29&doctype=Inline&ss=1&group=0&
verbose=1&uri='+escape(document.location))

source

JavaScript Set Cookie Midnight Expiration

function createCookie(name,value,path) {
	var expires = "";
	var date = new Date();
	var midnight = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
	expires = "; expires=" + midnight.toGMTString();
	if (!path) {
		path = "/";
	}
	document.cookie = name + "=" + value + expires + "; path=" + path;
}

source

Format a string with an array of arguments

/**
 * Format a string with an array of arguments.
 * 
 * @param msg A string.
 * @return A formatted string
 */
function format(msg) {
    if (arguments && arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            msg = msg.replace('{'+(i-1)+'}', arguments[i]);
        }
    }
    return msg;
}

source

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

Unique array in JavaScript

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(this[i] in u)
         continue;
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}

source

How to namespace your event handlers

$("div").bind("click.plugin", someFn);  
$("div").bind("focus.plugin", otherFn);  
$("div").unbind(".plugin");

source

Searching of all nodes on page for particular piece of text

/*This useful extended function will allow you to 
pattern match a keyword across all the nodes in a 
page. See the example below for how GMail use something 
similar in concept for their search-keyword highlighting*/  
  
$.fn.egrep = function(pat) {  
 var out = [];  
 var textNodes = function(n) {  
  if (n.nodeType == Node.TEXT_NODE) {  
   var t = typeof pat == 'string' ?  
    n.nodeValue.indexOf(pat) != -1 :  
    pat.test(n.nodeValue);  
   if (t) {  
    out.push(n.parentNode);  
   }  
  }  
  else {  
   $.each(n.childNodes, function(a, b) {  
    textNodes(b);  
   });  
  }  
 };  
 this.each(function() {  
  textNodes(this);  
 });  
 return out;  
};  
  
// Here's an example of using this to highlight  
//all the nodes on the page that contain the keyword  
//'jQuery'  
$("#testbutton").click(function()  
{  
var n = $('body').egrep(/jquery/i); 
for (var i = 0; i < n.length; ++i) 
{ 
   void($(n[i]).css('background', 'yellow'));  
 }  
});

source

How to retain information stripped from the DOM by .remove()

//In the below example  
$("p").click(function(){  
      $(this).toggleClass("off");  
    });  
    var p;  
    $("button").click(function(){  
      if ( p ) {  
        p.appendTo("body");  
        p = null;  
      } else {  
        p = $("p").detach();  
      }  
    });

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