docs:programming:javascript:javascript_notes

JavaScript Notes

<html>
<head>
<title>Javascript Page</title>
<script language="JavaScript" type="text/javascript"><!--
 
function init(){
  alert("Your browser supports scripting!");
}
 
--></script>
</head>
<body onload="javascript: init();">
<h1>Javascript Page</h1>
<noscript>This will print if the user agent does not support javascript</noscript>
 
<p>This will always print.</p>
 
<script language="JavaScript" type="text/javascript"><!--
  document.write("You can also run scripts within the body of the page.");
--></script>
 
</body>
</html>
  • The standard way is document.getElementById(“elemID”)
  • IE uses document.all(“elemID”)
  • Older Netscape browsers used document.layers[elemID]
  • A utility function to get the proper element reference, regardless of browser:
    function getElem(elemID){
    	if(document.all){
    		return document.all(elemID);
    	}else if(document.getElementById){
    		return document.getElementById(elemID);
    	}else if(document.layers){
    		return document.layers[elemID];
    	}
    }
     
    ...before doing anything with the object, you can make sure you have a valid object like this:
    var elem = getElem("SomeElementId");
    if(elem){
    	// elem is valid, so proceed with code
    }
<SCRIPT language="JavaScript">
 
<!-- This opens the HTML comments that will hide the script from old browsers
 
// javascript comment
......Javascript Statements.......
 
/*
multi-line
javascript
comment
*/
 
//--> This closes the comment section and the browser will read on normally
 
</SCRIPT>
// in the <head> section of an html page
<script type="JavaScript" src="scriptFilename.js"></script>
if(elem && typeof elem.property != "undefined"){
  // element property is valid - it is safe to use this property
}
 
if(elem && typeof elem.method != "undefined"){
  // element method is valid - it is safe to call this method
}
  • docs/programming/javascript/javascript_notes.txt
  • Last modified: 2008/08/03 00:25
  • by 127.0.0.1