Dhtml

Changing Styles
on the Fly

Dynamic HTML

Shortcuts

Overview
Part 1
Part 2
Part 3
Part 4

Overview

In this tutorial, you will learn how to use JavaScript to change the style of an element. This can be used to create interesting, interactive effects.


Part 1

When the user does almost anything to almost any element on a page, it is said that an event is triggered. Such events may be the user moving the mouse over an element or changing the focus of a form to a particular field. If the event isn't handled, then it is most likely that the event will go unnoticed. However, if an event handler exists for the event, then some action may be taken. An event handler is a JavaScript function that performs some procedure when an event occurs. Usually this procedure involves accessing or modifying the DOM.

To set up an event handler for an element, first write the JavaScript code for the function in a SCRIPT tag (the procedure for doing this is explained in the next section). Then you must assign the function to the event handler parameter in the tag of the element that triggers the event.

Let's say for instance that you want to change the background colour of a page when the user clicks on the name of the colour. Write a JavaScript function called changeBackground(color) and assign this to the onClick event handler of the name of the colour. Use the example below to do this (nb: SPAN is an inline tag with no default formatting styles that allows you to assign event handlers and styles to otherwise ordinary text. DIV is just like SPAN, except it is a tag for block elements).

<SPAN onClick=changeBackground('red')>Red</SPAN>

Other event handlers you may wish to use are onLoad, onUnload, onFocus, onBlur, onDblClick, onMouseDown, onMouseUp, onMouseOver, onMouseMove, onMouseOut, onKeyPress, onKeyDown, onKeyUp, onSubmit, onReset, onSelect, or onChange. Where you can use each of these handlers depends on the element. Refer to the Javascript Alphabetical Reference for more detail about each of these handlers.


Part 2

In order to get any use out of setting event handlers, you must actually write the handler function yourself (or perhaps modify a function written by someone else). This is where the real flexibility comes in to play. By writing your own code in event handler functions, you can do almost anything with your HTML pages.

To include any Javascript with your HTML page, you may either write the code in a separate file and import it, or include the code in a SCRIPT element in the HTML (or you can do both). To import a file, enter all of your Javascript into a file and save it with some name, for example "javascript.js". Then use the following tag in your HTML to include the Javascript from the file:

<SCRIPT language="JavaScript" src="javascript.js"></SCRIPT>

To include the Javascript directly in your HTML source in a SCRIPT tag, use the following syntax:

<SCRIPT language="JavaScript">
<!-- Comment out the code so older browsers ignore it

function myFirstJavaScript () {
   /* Prints the message "Hello World!" */
   document.write("Hello World!");
}

// -->
</SCRIPT>

The basic syntax of a Javascript function is:

function functionName ( [parameters] ) {
   [ declarations and statements ]
}

To find out about various declarations and statements you may use, refer to the Javascript Alphabetical Reference.


Part 3

Since the DOMs of Internet Explorer 4.0 and Netscape Navigator 4.0 differ, it is important to try and write JavaScript that achieves the same effect in both browsers. This "cross-browser" DHTML has been seen as the Holy-Grail for DHTML developers, since the lack of DOM standardisation allows for a lot of differences that need to be handled.

The most comment method of writing cross-browser JavaScript involves at least one function that is run when the HTML page opens (using the onLoad event handler) and detects which browser is running. Global variables are then used to translate (sometimes messy) normalised code into the appropriate syntax for each browser.

Below is some HTML source which shows an example of implementing cross-browser compatability. The init() function is called when the page loads and detemines which browser is running and sets the global variables accordingly. This code will be included in every JavaScript example throughout the rest of these tutorials.

<SCRIPT language="JavaScript">
<!--
var ns4, ie4, layerRef, linkRef, styleRef, pxRef, visibleRef;
   /*
   ** global variables used for cross-browser compatability.
   */

function init()
   /*
   ** init() initialises the global variables used for
   ** cross-browser compatability.
   */
   {
      ns4 = (document.layers) ? true : false;
      ie4 = (document.all) ? true : false;

      if (ns4) {
         layerRef   = "document.layers";
         linkRef    = "document.anchors";
         styleRef   = "";
         pxRef      = "";
         visibleRef = "show";
      } else if (ie4) {
         layerRef   = "document.all";
         linkRef    = "document.all";
         styleRef   = ".style";
         pxRef      = "px";
         visibleRef = "visible";
      } else {
         document.write('<html>\n
                         <head>\n
                         <title>Incompatible Browser</title>\n
                         </head>\n\n
                         <body>\n
                         <h1>Incompatible Browser</h1>\n\n
                         <p>\n
                         The browser you are using does not support 
                         DHTML. Please upgrade to <a 
                         href="http://www.microsoft.com/windows/ie/
                         default.htm">Microsoft Internet Explorer 4.0</a> 
                         or <a href="http://www.netscape.com/browsers/
                         index.html">Netscape Communicator/Navigator 
                         4.0</a>.\n
                         </p>\n
                         </body>\n
                         </html>\n');
   }

// -->
</SCRIPT>

<BODY onLoad=init()>

Part 4

Now it is time to put all of these basics together to create some aspect of interactivity on your page.

Below is an example of some HTML source which demonstrates the procedure for changing the background colour of the HTML page when the user clicks on the name of the colour.

<SCRIPT language=JavaScript>
<!--

function changeBackground(color) {
   /*
   ** changeBackground(color) changes the document background
   ** colour to color.
   */
   if (ns4) {
      document.bgcolor = color;
   } else if (ie4) {
      document.body.style.backgroundColor = color;
   }
}

// -->
</SCRIPT>

<STYLE type="text/css">
<!--

.FakeA {
   text-decoration: underline;
   color: rgb(140,160,255);
   cursor: hand;
}

// -->
</STYLE>

<P>
<SPAN onclick=changeBackground('red') class=FakeA>red</SPAN><BR>
<SPAN onclick=changeBackground('orange') class=FakeA>orange</SPAN><BR>
<SPAN onclick=changeBackground('yellow') class=FakeA>yellow</SPAN><BR>
<SPAN onclick=changeBackground('green') class=FakeA>green</SPAN><BR>
<SPAN onclick=changeBackground('blue') class=FakeA>blue</SPAN><BR>
<SPAN onclick=changeBackground('violet') class=FakeA>violet</SPAN>
</P>

Click on any of the colour names below for a demonstration of the code.

red
orange
yellow
green
blue
violet



Go back


Author: Scott Brady
Date Created: 4 May 99
Last Updated: