JavaScript Tips and Tricks

  1. For a select box that allows only one option to be selected, the easiest way to access the selected option is by using the select box's selectedIndex property to retrieve the option, as shown in the following example:
    var selectedOption = selectbox.options[selectbox.selectedIndex];
  2. A good way to use JavaScript to prevent the user from impatiently submitting a <form> multiple times is to disable the submit after it has been pushed. Give the disabled property a value of true.
  3. The following code can figure out the pageX and pageY on all browsers.
    
    var div = document.getElementById("someDiv");
    div.onclick = function(event){
    	var pageX = event.pageX, pageY = event.pageY;
    	if (pageX === undefined){
    		pageX = event.clientX + (document.body.scrollLeft || document.documentElement.scrollLeft);
    	}
    	if (pageY === undefined){
    		pageY = event.clientY + (document.body.scrollTop || document.documentElement.scrollTop);
    	}
    	alert("Page coordinates: " + pageX + "x" + pageY);
    };
    
  4. The following code can be used to parse location.search
    
    function parseQueryString(){
    var qs = (location.search.length > 0 ? location.search.substring(1) : ""), args = {}, items = (qs.length ? qs.split("&") : []), item = null, name = null, value = null, i = 0, len = items.length;
    for (i=0; i < len; i++){
    	item = items[i].split("=");
    	name = decodeURIComponent(item[0]);
    	value = decodeURIComponent(item[1]);
    	if (name.length) {
    		args[name] = value;
    	}
    }
    return args;
    }
    
  5. Have code execute when the document is done loading:
    <script type="text/javascript">
    	window.onload = function () {
    		var hello = "Hello, World!";
    		alert(hello);
    	};
    </script>
  6. Have code execute without specifying the onload event and to have it execute immediately, before the document is done loading:
    <script type="text/javascript">
    	(function () {
    		alert("hello");
    	}(document));
    </script>
  7. The setTimeout() function runs some code after a set amount of milliseconds. It is good for animating an object on the HTML <canvas> tag.
    <script type="text/javascript">
    	var timerId = setTimeout(function () { alert("hello"); }, 2000);
    </script>
  8. The clearTimeout() function cancels the setTimeout().
    <script type="text/javascript">
    	clearTimeout(timerId);
    </script>
  9. The setInterval() function keeps running code after every set number of milliseconds.
    <script type="text/javascript">
    	var timerId = setInterval(function () { alert("hello"); }, 2000);
    </script>
  10. The clearInterval() function cancels the setInterval().
    <script type="text/javascript">
    	clearInterval(timerId);
    </script>
  11. Set the header of a XMLHttpRequest() post:
    var x = XMLHttpRequest();
    x.open("post", action, true);
    x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    // OR
    x.setRequestHeader("Content-Type", "multipart/form-data");
    x.send(body);
    
  12. When nothing is known about an object, iterate through its properties to discover it. This code is compatible with older browsers. For modern browsers, this is not neccessary.
    <script type="text/javascript">
    	var objDemo = {
    		id: 1234,
    		first_name: "John",
    		last_name: "Smith",
    		address: {
    			street: "123 Abc Ln.",
    			city: "San Francisco",
    			state: "California"
    		},
    		email: "jsmith@smithdomain.com"
    	}
    
    	for(var prop in objDemo){
    		if(typeof(objDemo[prop]) == "object"){
    			for(var prop2 in objDemo[prop]){
    				alert("objDemo." + prop + "." + prop2 + "=" + objDemo[prop][prop2]);
    			}
    		}
    		else {
    			alert("objDemo." + prop + "=" + objDemo[prop]);
    		}
    	}
    </script>
  13. This will move an element, like a <DIV>, in the opposite direction of the mouse to expose all the hidden areas.
    //the surrounding div should have its CSS overflow:hidden; adjust_left and adjust_top are numbers
    function mousemoveDiv(event, pic_width, pic_height, div_object, adjust_left, adjust_top) {
    	var offX = 0;
    	var offY = 0;
    	if(window.pageYOffset){
    		offX = window.pageXOffset;
    		offY = window.pageYOffset;
    	}
    	else{
    		if(document.documentElement.scrollTop == 0){
    			offX = document.body.scrollLeft;
    			offY = document.body.scrollTop;
    		}
    		else{
    			offX = document.documentElement.scrollLeft;
    			offY = document.documentElement.scrollTop;
    		}
    	}
    	var divWidth = parseInt(div_object.style.width);
    	var divHeight = parseInt(div_object.style.height);
    	var x;
    	var y;
    	if (event.pageX) {
    		x = (event.pageX - offX);
    		y = (event.pageY - offY);
    	}
    	else {
    		x = (event.clientX - offX);
    		y = (event.clientY - offY);
    	}
    	div_object.style.left = (parseInt((divWidth - pic_width) * (x / divWidth)) + adjust_left) + "px";
    	div_object.style.top = (parseInt((divHeight - pic_height) * (y / divHeight)) + adjust_top) + "px";
    }