JavaScript Tips & Tricks
CONTENTS
Prevent Backspace from doing a History Back
Calling an object's method in a timeout
Element references
Programmatic Submission
Submit via Enter key
Radio toggle buttons
Creating a set of radio toggles
Getting the value from a set of radio toggles
Setting the checked radio toggle
Useful DOM Methods
Hiding and Showing
Make a text scroll

Prevent Backspace from doing a History Back

If the focus is not in a text control, hitting the backspace key will do a History Back to the preceding page in many browsers. This is ridiculously annoying. Here's how to prevent it (in IE at least, not tested elsewhere yet):
// add an even handler to the document to prevent hitting // the backspace key when no text has the focus from // invoking the history back functionality // we want the backspace key to still be active on text fields and text areas, // but only if they're active (i.e. not disabled and not read only document.onkeydown = function() { if (window.event) { if (window.event.keyCode == 8) { var src = window.event.srcElement; var tag = src.tagName ? src.tagName.toUpperCase() : ''; var typ = (tag == 'INPUT') ? src.type.toUpperCase() : ''; var isTextArea = (tag == 'TEXTAREA'); var isTextField = ((tag == 'INPUT') && (typ == 'TEXT')); var isText = isTextField || isTextArea; var disabled = isText ? src.disabled : false; var readOnly = isText ? src.readOnly : false; if (!isText || disabled || readOnly) { window.event.cancelBubble = true; window.event.returnValue = false; return false; } } } }</doc:example> </doc:section> <doc:section name="Redefining an onload function"> <doc:item>Sometimes, you want to define an onload function, but you're in some included files, and you don't even know if one has been defined already. Here's what to do:</doc:item> <doc:example><![CDATA[ function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } function whatever() { // do something } addLoadEvent(whatever);
to top

Calling an object's method in a timeout

This is tricky, since the timeout methods only take a function argument - no way to specify the object whose method should be called. But you can get around this problem, by using the "apply" method that's available for any function:
var obj = new Object(); obj.method = function(arg1, arg2) { // do something... } setTimeout(function() { obj.method.apply(obj, [ 23, 'skidoo' ]); }, 100); }
to top

Element references

document.all['name'] - standard in IE, works in Mozilla, but gives warning
document.getElementById('id') - IE & Mozilla, but item must have unique id
document.getElementsByName('name').item(0) - IE & Mozilla, works when item has a unique nam
to top

Programmatic Submission

Sometimes, you need to submit a form programmatically. If there are multiple submit buttons in the form, then you probably also need the correct button to contribute its name/value pair to the submitted parameters. To do this, you must set the focus on the button first, like this:
var b = document.getElementById('thebutton'); b.focus(); b.submit();
If you don't do the focus, you don't get the button's name/value pair.
to top

Submit via Enter key

In IE, pressing the Enter key submits the form, using the submit button that currently has the focus. If no submit button has the focus, then it submits using the first appearing submit button in the form. If this is awkward, you can get around it by means of the technique described in the preceding section. This page provides more details.
to top

Radio toggle buttons

Creating a set of radio toggles

<form name='main'> <input type='radio' name='fred' value='0'>&amp;nbsp;Apples <input type='radio' name='fred' value='1'>&amp;nbsp;Oranges <input type='radio' name='fred' value='2' checked>&amp;nbsp;Pears </form>
It doesn't hurt to stick an &nbsp; before the label - Netscape always bangs them up too close.
The above produces:
<form name='main'> <input type='radio' name='fred' value='0'>&nbsp;Apples <input type='radio' name='fred' value='1'>&nbsp;Oranges <input type='radio' name='fred' value='2' checked>&nbsp;Pears </form>

Getting the value from a set of radio toggles

var value = ''; for (var i = 0; i < document.main.fred.length; i++) { if (document.main.fred.checked) { value = document.main.fred.value; } }

Setting the checked radio toggle

document.main.fred[1].checked = true;
to top

Useful DOM Methods

// get the one element with the id var a = document.getElementById('div3'); // get an array of elements having the tag (e.g. p, div, etc.) var b = document.getElementsByTagName('div'); // given an element, get the array of children var c = b.childNodes; // given an element, get an attribute var d = b.getAttribute('length'); // setting an attribute d.setAttribute('length', '20'); // listing all attributes for (var attr = 0; attr < b.attributes.length; attr++ ) { if (b.attributes[attr].nodeName.toLowerCase() == 'size' ) { alert('size = ' + b.attributes[attr].nodeValue); } } // remove an attribute d.removeAttribute('temp'); // create a node var e = document.createElement('div'); var t = document.createTextNode('some text'); // managing children b.appendChild(e); e.appendChild(t); b.insertBefore(e, document.createTextNode('again')); e.parentNode.removeChild(e); // creating text var t = document.createTextNode('some text'); // changing text t.nodeValue = 'some other text'; // creating an &nbsp; var u = document.createTextNode('\u00a0'); // managing tables // a table element contains a caption, a thead, an array of // tbodies, and a tfoot // the rows are children of the tbodies... so to create a table var t = document.createElement('table'); var tb = document.createElement('tbody'); var r = document.createElement('tr'); var c = document.createElement('td'); var txt = document.createTextElement('data'); c.appendChild(txt); r.appendChild(c); tb.appendChild(r); t.appendChild(tb);
to top

Hiding and Showing

// showing and hiding - ghost space disappears if (e.style.display=="block") { e.style.display="none" } else { e.style.display="block" } // showing and hiding - ghost space remains if (e.style.visibility=="visible") { e.style.display="hidden" } else { e.style.display="visible" }
to top

Make a text scroll

textareaname.scrollTop = textareaname.scrollHeight;
to top