PROWAREtech
JavaScript: Tips and Tricks
Useful tips and tricks for the budding JavaScript programmer.
-
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;
-
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; }
-
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];
-
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 thedisabled
property a value oftrue
. -
The following code can figure out the
pageX
andpageY
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); };
-
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; }
-
Have code execute when the document is done loading:
<script type="text/javascript"> window.onload = function () { var hello = "Hello, World!"; alert(hello); }; </script>
-
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>
-
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>
-
The
clearTimeout()
function cancels thesetTimeout()
.<script type="text/javascript"> clearTimeout(timerId); </script>
-
The
setInterval()
function keeps running code after every set number of milliseconds.<script type="text/javascript"> var timerId = setInterval(function () { alert("hello"); }, 2000); </script>
-
The
clearInterval()
function cancels thesetInterval()
.<script type="text/javascript"> clearInterval(timerId); </script>
-
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);
-
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>
-
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"; }
Comment