Tag Archive for javascript

Only allow AJAX for a HTTP Request

// If the request did not come from AJAX, exit:
if($_SERVER['HTTP_X_REQUESTED_WITH'] !='XMLHttpRequest'){
	exit;
}

source

Using Input Title As Initial Text – Hide When On Focus

function watermark ($obj) {
				
	var prev;
	
	$obj.each(function() {
		if ($(this).attr("title"))	$(this).val($(this).attr("title")).addClass("greyout");
	});
	
	$obj
		.focus(function()
			{
				if ($(this).val()==$(this).attr("title")) {
					prev = $(this).val();
					$(this).val("").removeClass("greyout");
				}
			})
		
		.blur(function()
			{
				if($(this).val()=="") {
					$(this).val(prev).addClass("greyout");;
				}
			});

}

source

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