Page is a not externally linkable
- Code, Content, and Presentation
-- JavaScript and AJAX
---- How to define a global variable for all the functions


rocknbil - 5:26 pm on Jan 17, 2012 (gmt 0)


^^ @ Fotiman: you've said this often, how is it superior to window.onload = function() {};? Just curious.

I try to avoid globals altogether. Pass parameters. Here's another one to pick apart. :-)


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Sample form</title>
<script type="text/javascript">
window.onload=function() { attachBehaviors(); }
// Attach behaviors and say NO to inline JS. :-)
function attachBehaviors() {
var obj = document.getElementById('myInput');
if (obj) {
obj.onfocus=function() {
if (obj.value==obj.defaultValue) { obj.value=''; }
}
obj.onblur=function() {
if (obj.value=='') { obj.value=obj.defaultValue; }
}
} // if obj
var frm = document.getElementById('myForm');
if (frm) {
frm.onsubmit=function() { return displayResult(); }
}
} // function
//
function displayResult() {
var obj = document.getElementById('myInput');
if (obj) {
alert((obj.value=='')?'No Value!':obj.value);
}
return false;
}
</script>
</head>
<body>
<form name="myForm" id="myForm" method="get" action="">
<p>When you move to the button you blur. So to see the effect of
&quot;no value&quot; click into the text field and press enter.</p>
<p><input name="myInput" id="myInput" value="Hello world!"></p>
<p><input type="submit" value="Display input value"></p>
</form>
</body>
</html>


Thread source:: http://www.webmasterworld.com/javascript/4407663.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com