Get selected text of an web page including textarea,input box and anchor tag

The JavaScript code below fetches the value anywhere in a page including textarea, input and text fields of the forms.

function GetSelectedText()
{
  var selectedText=(
        window.getSelection
        ?
            window.getSelection()
        :
            document.getSelection
            ?
                document.getSelection()
            :
                document.selection.createRange().text
     );
 if(!selectedText || selectedText=="")
 {
    if(document.activeElement.selectionStart)
    {
     selectedText = document.activeElement.value.substring(
          document.activeElement.selectionStart
          . document.activeElement.selectionEnd);
    }
 }
 return selectedText;
}

The Above code is collected from this url(http://www.codeproject.com/Articles/292159/Javascript-code-to-get-selected-text#) so all the credits goes to him.

Js Arguments

The arguments object is a local variable available within all functions; arguments as a property of Function can no longer be used.

You can refer to a function’s arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry’s index starting at 0. For example, if a function is passed three arguments, you can refer to the argument as follows:

arguments[0]
arguments[1]
arguments[2]

The arguments object is not an array. It is similar to an array, but does not have any array properties except length. For example, it does not have the pop method. However it can be converted to a real array:

var args = Array.prototype.slice.call(arguments);

The arguments object is available only within a function body. Attempting to access the arguments object outside a function declaration results in an error.

You will get more details about this topics here:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments
**Another well explanation will found here:
http://blog.sebarmeli.com/2010/11/12/understanding-array-prototype-slice-applyarguments/

Jquery Image Preload

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

jQuery.preLoadImages("image1.gif", "/path/to/image2.png");

source : http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript

parseUri 1.2: Split URLs in JavaScript

This code was originally posted by Steve in ‘http://blog.stevenlevithan.com/archives/parseuri’. I just copied from his blog. You can get details about this function to above url. This is very efficient and useful function for url parsing.

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

Javascript manipulate contents by class name like ID

Most of us use ID to access or manipulate html DOM, But it can be done with class name which is little bit tricky. I have done it on one of my firefox plugin project.


var target_class = document.getElementsByClassName("div_content")[0];// Search the class
clearChildNodes(target_class);//Remove Child nodes of the class

var div1 = document.createElement("div");//create a new element
div1.setAttribute('class', 'child_div1');// Add class name to the newly created element

target_class .appendChild(div1);// Append the new element to the target div


function clearChildNodes(node) {
    if (node.childNodes.length &gt; 0) {
        while(node.hasChildNodes()) {
            node.removeChild(node.firstChild);
        }
    }
    return node;
}

Money Format(us currency)

    
formatCurrency:function (num) {
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
            num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
            cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
            num = num.substring(0,num.length-(4*i+3))+','+
            num.substring(num.length-(4*i+3));
            if(cents==00) return (((sign)?'':'-') + num );
            else
            return (((sign)?'':'-') + num + '.' + cents);
    }
 

Strip HTML using JavaScript


function htmlToText(html) {
return html
// Remove line breaks
.replace(/(?:\n|\r\n|\r)/ig,"")
// Turn <br>'s into single line breaks.
.replace(/<\s*br[^>]*>/ig,"\n")
// Turn </li>'s into line breaks.
.replace(/<\s*\/li[^>]*>/ig,"\n")
// Turn <p>'s into double line breaks.
.replace(/<\s*p[^>]*>/ig,"\n\n")
// Remove content in script tags.
.replace(/<\s*script[^>]*>[\s\S]*?<\/script>/mig,"")
// Remove content in style tags.
.replace(/<\s*style[^>]*>[\s\S]*?<\/style>/mig,"")
// Remove content in comments.
.replace(/<!--.*?-->/mig,"")
// Format anchor tags properly.
// e.g.
// input - <a class='ahref' href='http://pinetechlabs.com/' title='asdfqwer\"><b>asdf</b></a>
// output - asdf (http://pinetechlabs.com/)
.replace(/<\s*a[^>]*href=['"](.*?)['"][^>]*>([\s\S]*?)<\/\s*a\s*>/ig, "$2 ($1)")
// Remove all remaining tags.
.replace(/(<([^>]+)>)/ig,"")
// Make sure there are never more than two
// consecutive linebreaks.
.replace(/\n{2,}/g,"\n\n")
// Remove tabs.
.replace(/\t/g,"")
// Remove newlines at the beginning of the text.
.replace(/^\n+/m,"")
// Replace multiple spaces with a single space.
.replace(/ {2,}/g," ")
// Decode HTML entities.
.replace(/&([^;]+);/g, decodeHtmlEntity );
}

function decodeHtmlEntity(m, n) {
// Determine the character code of the entity. Range is 0 to 65535
// (characters in JavaScript are Unicode, and entities can represent
// Unicode characters).
var code;

// Try to parse as numeric entity. This is done before named entities for
// speed because associative array lookup in many JavaScript implementations
// is a linear search.
if (n.substr(0, 1) == '#') {
// Try to parse as numeric entity
if (n.substr(1, 1) == 'x') {
// Try to parse as hexadecimal
code = parseInt(n.substr(2), 16);
} else {
// Try to parse as decimal
code = parseInt(n.substr(1), 10);
}
} else {
// Try to parse as named entity
code = ENTITIES_MAP[n];
}

// If still nothing, pass entity through
return (code === undefined || code === NaN) ?
'&' + n + ';' : String.fromCharCode(code);
}

var ENTITIES_MAP = {
'nbsp' : 160,
'iexcl' : 161,
'cent' : 162,
'pound' : 163,
'curren' : 164,
'yen' : 165,
'brvbar' : 166,
'sect' : 167,
'uml' : 168,
'copy' : 169,
'ordf' : 170,
'laquo' : 171,
'not' : 172,
'shy' : 173,
'reg' : 174,
'macr' : 175,
'deg' : 176,
'plusmn' : 177,
'sup2' : 178,
'sup3' : 179,
'acute' : 180,
'micro' : 181,
'para' : 182,
'middot' : 183,
'cedil' : 184,
'sup1' : 185,
'ordm' : 186,
'raquo' : 187,
'frac14' : 188,
'frac12' : 189,
'frac34' : 190,
'iquest' : 191,
'Agrave' : 192,
'Aacute' : 193,
'Acirc' : 194,
'Atilde' : 195,
'Auml' : 196,
'Aring' : 197,
'AElig' : 198,
'Ccedil' : 199,
'Egrave' : 200,
'Eacute' : 201,
'Ecirc' : 202,
'Euml' : 203,
'Igrave' : 204,
'Iacute' : 205,
'Icirc' : 206,
'Iuml' : 207,
'ETH' : 208,
'Ntilde' : 209,
'Ograve' : 210,
'Oacute' : 211,
'Ocirc' : 212,
'Otilde' : 213,
'Ouml' : 214,
'times' : 215,
'Oslash' : 216,
'Ugrave' : 217,
'Uacute' : 218,
'Ucirc' : 219,
'Uuml' : 220,
'Yacute' : 221,
'THORN' : 222,
'szlig' : 223,
'agrave' : 224,
'aacute' : 225,
'acirc' : 226,
'atilde' : 227,
'auml' : 228,
'aring' : 229,
'aelig' : 230,
'ccedil' : 231,
'egrave' : 232,
'eacute' : 233,
'ecirc' : 234,
'euml' : 235,
'igrave' : 236,
'iacute' : 237,
'icirc' : 238,
'iuml' : 239,
'eth' : 240,
'ntilde' : 241,
'ograve' : 242,
'oacute' : 243,
'ocirc' : 244,
'otilde' : 245,
'ouml' : 246,
'divide' : 247,
'oslash' : 248,
'ugrave' : 249,
'uacute' : 250,
'ucirc' : 251,
'uuml' : 252,
'yacute' : 253,
'thorn' : 254,
'yuml' : 255,
'quot' : 34,
'amp' : 38,
'lt' : 60,
'gt' : 62,
'OElig' : 338,
'oelig' : 339,
'Scaron' : 352,
'scaron' : 353,
'Yuml' : 376,
'circ' : 710,
'tilde' : 732,
'ensp' : 8194,
'emsp' : 8195,
'thinsp' : 8201,
'zwnj' : 8204,
'zwj' : 8205,
'lrm' : 8206,
'rlm' : 8207,
'ndash' : 8211,
'mdash' : 8212,
'lsquo' : 8216,
'rsquo' : 8217,
'sbquo' : 8218,
'ldquo' : 8220,
'rdquo' : 8221,
'bdquo' : 8222,
'dagger' : 8224,
'Dagger' : 8225,
'permil' : 8240,
'lsaquo' : 8249,
'rsaquo' : 8250,
'euro' : 8364
};
 

How to inspect javascript Object property

This is a useful tool whenever you work with JavaScript and the compatibility issues between navigators.

You can inspect any JavaScript objects and list them as indented, ordered by levels.
It shows you type and property name. If an object property can’t be accessed, an error message will be shown.

Using the Code

function inspect(obj [, maxLevels [, level]])

Input Vars

obj: Object to inspect
maxLevels: Optional. Number of levels you will inspect inside the object. Default MaxLevels=1
level: RESERVED for internal use of the function

Return Value

HTML formatted string containing all values of inspected object obj.

function inspect(obj, maxLevels, level)
{
	var str = '', type, msg;	
	// Start Input Validations	
	// Don't touch, we start iterating at level zero	
	if(level == null) level = 0;	
	// At least you want to show the first level	
	if(maxLevels == null) maxLevels = 1;	
	if(maxLevels < 1)	
	return '<font color="red">Error: Levels number must be > 0</font>';	
	// We start with a non null object	
	if(obj == null)	
	return '<font color="red">Error: Object <b>NULL</b></font>';	
	// End Input Validations	
	// Each Iteration must be indented	
	str += '<ul>';	
	// Start iterations for all objects in obj

	for(property in obj)
	{
		try	
		{	
			// Show "property" and "type property"
			
			type = typeof(obj[property]);	
			str += '<li>(' + type + ') ' + property +	
			( (obj[property]==null)?(': <b>null</b>'):('')) + '</li>';	
			// We keep iterating if this property is an Object, non null	
			// and we are inside the required number of levels	
			if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))	
			str += inspect(obj[property], maxLevels, level+1);	
		}
	
		catch(err)	
		{	
			// Is there some properties in obj we can't access? Print it red.		
			if(typeof(err) == 'string') msg = err;		
			else if(err.message) msg = err.message;		
			else if(err.description) msg = err.description;		
			else msg = 'Unknown';		
			str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';	
		}
	}

	// Close indent
	str += '</ul>';
	return str;
}