18 June 2005

onload javascript

1) Simple way to focus on input text when the page is first loaded.
<body onload='document.myform.foc.focus();'>
2) If javascript in an external file, we need to use other way.
window.onload = document.myform.foc.focus;
Note that, neglected () at the end and window.onload will execute once the page has finished loading. Drawback, if contain multiple script, the last window.onload will the only script to execute.

3) Dynamic one:
function addEvent(obj, evType, fn){
if (obj.addEventListener){
obj.addEventListener(evType, fn, true);
return true;
} else if (obj.attachEvent){
var r = obj.attachEvent('on'+evType, fn);
return r;
} else {
return false;
}
}

addEvent(window, 'load', function() {
document.myform.foc.focus()
});


Usable form, example
Enhance structural markup with javascript, example

No comments: