PROWAREtech

articles » current » javascript » tips-and-tricks

JavaScript: Tips and Tricks

Useful tips and tricks for the budding JavaScript programmer.
  1. Get the height of an HTML element with offsetHeight but if the element is not being displayed then this returns 0.
    var element_height = document.getElementById("id").offsetHeight;
  2. Here are some useful prototypes:
    if (!String.prototype.trim) { // string.trim()
    	String.prototype.trim = function () {
    		return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
    	};
    }
    if (!Array.isArray) { // Array.isArray()
    	Array.isArray = function (arg) {
    		return Object.prototype.toString.call(arg) == "[object Array]";
    	};
    }
    function isObjectEmpty(obj) { // determines if an object is empty (has no properties)
      for(var prop in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, prop)) {
          return false;
        }
      }
      return true;
    }
    
  3. 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];
  4. 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.
  5. 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);
    };
    
  6. 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;
    }
    
  7. Have code execute when the document is done loading:
    <script type="text/javascript">
    	window.onload = function () {
    		var hello = "Hello, World!";
    		alert(hello);
    	};
    </script>
  8. Immediately Invoked Function Expression: 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>
  9. 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>
  10. The clearTimeout() function cancels the setTimeout().
    <script type="text/javascript">
    	clearTimeout(timerId);
    </script>
  11. The setInterval() function keeps running code after every set number of milliseconds.
    <script type="text/javascript">
    	var timerId = setInterval(function () { alert("hello"); }, 2000);
    </script>
  12. The clearInterval() function cancels the setInterval().
    <script type="text/javascript">
    	clearInterval(timerId);
    </script>
  13. Set the header of a XMLHttpRequest() regular post (application/x-www-form-urlencoded):
    var x = XMLHttpRequest();
    x.open("post", action, true);
    x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    x.send(body);
    
  14. 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>
  15. 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(typeof window.pageXOffset != "undefined"){
    		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 (typeof event.pageX != "undefined") {
    		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";
    }
    

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE