Scripting for 5th Generation Browsers and Beyond - Part I - (1/7) | WebReference

Scripting for 5th Generation Browsers and Beyond - Part I - (1/7)

current pageTo page 2To page 3To page 4To page 5To page 6To page 7
[next]

Scripting for 5th Generation Browsers and Beyond

[Editor's note: all "live examples" within this article open in a new window unless otherwise specified.]

Code Reduction

One of the biggest benefits of coding for IE5+ and Netscape 6+ is the code reduction that is obtained by not having to include conditional branches (e.g. If/else statements). For example, let us suppose we wanted to dynamically change the background color of a layer in Netscape 4, Internet Explorer 4, and Internet Explorer 5+/Netscape 6+. We would have to create conditional statements to cater to the different Document Object Models as demonstrated in the below example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Change The Background Color</title>
<script>
function changelayerColor() {
if (document.all)
  document.all.Layer1.style.backgroundColor = 'red';
else if (document.getElementById)
  document.getElementById('Layer1').style.backgroundColor = 'red';
else if (document.layers)
  document.Layer1.bgColor = 'red';
}
</script>
</head>
<body bgcolor="#FFFFFF" text="#000000">
<a href="#" onMouseover="changelayerColor()">Change 
   Layer Background Color</a>
<div id="Layer1" 
     style="position:absolute; width:200px; height:115px; 
     z-index:1; left: 203px; top: 84px; 
     background-color: #0066FF; layer-background-color: #0066FF; 
     border: 1px none #000000"></div>
</body>
</html>

However, if you wanted to code by W3C standards the above script would translate as such: (live example)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>W3C Change Layer Background Color</title>
<script>
function changeColor() {
   document.getElementById('Layer1').style.backgroundColor = 'red';
 }
</script>
</head>
<body bgcolor="#FFFFFF" text="#000000">
<a href="#" onMouseover="changeColor()">Change Layer Background Color</a>
<div id="Layer1" 
    style="position:absolute; width:200px; height:115px; z-index:1; 
    left: 203px; top: 84px; background-color: #0066FF"></div>
</body>
</html>

As is demonstrated in the above example, there is a considerable reduction in the code. The above script functions in Internet Explorer 5+ and Netscape 6+ as these both support the W3C DOM document.getElementById() method. At last a standard way of scripting that is compatible in both browsers! From my perspective, that is the real benefit of coding in such a manner.

Contents:

current pageTo page 2To page 3To page 4To page 5To page 6To page 7
[next]


Created: August 16, 2001
Revised: August 16, 2001

URL: http://webreference.com/programming/javascript/domscripting/1/