Tutorial Redirect to SSL

by in , 0

window.location = "https://" + window.location.hostname + window.location.pathname + window.location.search;

You might wanna test if window.location.href doesn't start with "https" before doing that, so you don't redirect unless you have to.

Tutorial Redirect

by in , 0

<script type="text/javascript">
<!--
  window.location = "http://www.google.com/"
//-->
</script>

Tutorial Random Hex Color

by in , 0

var randomColor = Math.floor(Math.random()*16777215).toString(16);

View Demo

There is also a PHP version.

Reference URL

Tutorial Put Comma Values in Numbers

by in , 0

This function assumes what is being submitted to it is a string, with a decimal point and two places after the decimal. To get your number into that format first, use this.

Then this function will properly comma separate the number. For example, 2345643.00 will return 2,345,643.00

function CommaFormatted(amount) {
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3) {
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}

Tutorial Print Object To Screen

by in , 0

PHP has a nice print_r function for printing out information about a variable to the screen. console.log() is great for that in JavaScript also, but sometimes you just need/want to look at it on the screen.

function print_r(o) {
  return JSON.stringify(o,null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;'); 
}

So if you have an object like:

var myObject = {
   "lunch": "sandwich",
   "dinner": "stirfry"
};

You could do:

var putHere = document.getElementById("#put-here");

putHere.innerHTML = print_r(myObject);

to see the result on screen.

Also, console.table() is sometimes much better than console.log() for this kind of thing.

Tutorial Prevent Embedded JavaScript from Failing Validation

by in , 0

Ever see that CDATA stuff in JavaScript and wonder what it was for? It is to prevent the validator from reading that code as markup and failing validation. For example, ampersands (&) and greater-than / less-than signs (< >)are often culprits for failing validation when it's actually perfectly OK to use them in JavaScript.

<script type="text/javascript">
  //<![CDATA[

    alert("<This is compatible with XHTML>");

  //]]>
</script> 

Tutorial Prevent Background Image Flickering in IE

by in , 0

try {
 document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}