News Outline Schedule Tutorials Project Tools Links

1: Applying an event

In most cases, a DHTML event would be applied to your web page as an attribute on some tag or other - the value of that attribute contains some Javascript which will be run every time the DHTML event you used occurs on that tag. As far as the browser is concerned, the contents of that attribute's value is just like the contents of a script tag, with only two exceptions:

  1. You can not have a newline character inside of an attribute value! This means that the javascript code for your event must be all typed on one line. Most often, this problem is avoided by creating a function to hold the actual javascript code, and just running the function itself as the attribute value.
  2. You can not include double quotes inside of double quotes, or single quotes inside of single quotes! This means that your javascript inside of the attribute value will be limited in the number of quotation marks it can use. Output which includes quotation marks can not easily be produced from within an event's attribute value. Again, this problem is avoided by creating a function to hold the actual javascript code, and just running the function itself as the attribute value.

2: Events vs Tags

In many cases, it can be difficult to determine which events are most apropriate to use on which XHTML tags. Remember in all cases, that the event should be applied as an attribute to the tag which the event will occur on - thus, if you are waiting for a button to be clicked on, place your "onclick" attribute on the tag which creates the button. Similarily, if you are waiting for a form to be submitted, the "onsubmit" event belongs on the form tag, not the submit button itself - after all, it's the form which is being submitted, not just the submit button. Below is a table listing commonly used DHTML events, and which tags they are most apropriately used on. Note that it is possible to use these events on other tags, but in many cases, they will either have no effect or not really be apropriate. (For example, onchange can easily be applied to an input tag of type button, but since the button will never change, the event is not likely to ever get triggered. Also, bear in mind that older browsers such as Netscape 4 do not fully support all of these events in the way listed below. (If the event in question includes an 'a' tag, Netscape 4 is most likely to only allow it on either 'a' tags, or form inputs.)

Event:What happens?Tags most apropriately used on:
onload Whole page has been loaded by browserbody
onunload Browser has left the current pagebody
onsubmit HTML form has been submitted (usually by clicking on the "submit" button)form
onreset HTML form has been reset (usually by clicking on the "reset" button)form
onmouseover Mouse has entered the area covered by the tag used img, a, div
onmouseout Mouse has exited the area covered by the tag used img, a, div
onfocusCurrent 'focus' has been passed to this tag a, textarea, select, input (any type)
onblurCurrent 'focus' has moved from this tag to somewhere else a, textarea, select, input (any type)
onclick Mouse has clicked once on this tag img, a, input (type button)
ondblclick Mouse has clicked twice on this tag img, a, input (type button)
onmousedown The mouse button has been pressed down img, a, input (type button)
onmouseup The mouse button was pressed down, and has just been released img, a, input (type button)
onkeypressUser has pressed and released a keyboard key while this tag held the focus textarea, input (type text/password)
onkeydown User has pressed a keyboard key while this tag held the focus textarea, input (type text/password)
onkeyup User has released a keyboard key while this tag held the focus textarea, input (type text/password)
onchange An input item has been altered - usually trigered at same time as onblur select, textarea, input (any type except button)
mousemove The mouse cursor has moved on the screen *special, must be set in Javascript
onerror One of a specific set of Javascript errors has occured *special, must be set in Javascript
setInterval()A specific ammount of time has gone by *special, must be set in Javascript

Except for setInterval(), examples of how to use each of these events are given on the Examples of Events page. Simply load the example page, and use view source from your browser to see the code for the example.

3: setInterval() - Using time as an event!

The setInterval() function allows you to take advantage of a major recurring event which happens in all browsers even without their user doing anything - the computer's clock ticking. Since the computer's clock is obviously not an XHTML tag, there is a special way of dealing with this - you can schedule many events to occur every time a certain ammount of time has passed. (ie: every 1000 miliseconds...) The setInterval() function has two parameters, first you need to give it some JavaScript to run whenever the timer comes up, and second you must provide the number of milliseconds between each time the event occurs. (Remember, Javascript always measures time in milliseconds. That's only 1/1000 of a second, so your numbers here will need to be large!) Lastly, and most importantly, setInterval() returns a special identifier for the event you've just scheduled - if you want to be able to stop that event later on, you must save that identifier!

<script type="text/javascript" language="javascript"> var potatoe; potatoe = setInterval( "runMe()", 2000); </script>

The above example creates a repeating event which will run a javascript function called "runMe()" every two seconds. (2000 milliseconds makes 2 seconds.) The identifier has then been stored in a variable called potatoe, which we can use later to stop the event, with another function called clearInterval(), like this:

clearInterval(potatoe);

4: Putting it all together

Below is an example of how you would use a combination of Style Sheets, Document Object Model, and DHTML Events to produce features in your web site. The example given below is a very simplified version of the menu system used for the class web pages. Even in this simplified version, it uses many different DHTML events, and depends very heavily on Style Sheet properties being set properly. A real copy of this file can be found here.

<?xml version="1.0" encoding="us-ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>?</title> <style type="text/css"> #theMenu { position: absolute; top: 1px; left: 1px; visibility: hidden; width: 130px; line-height: 0; z-index: 300; } #menuImg { position: absolute; top: 1px; left: 1px; visibility: visible; z-index: 100; } </style> <script type="text/javascript"> <!-- var closeInterval; // Menu Closing flag var mPointer; // The Menu function setupMenu() { // All we really need to do here is get the pointer to the menu if (document.layers) { // Netscape 4 accesses things in odd ways... mPointer = window.document.theMenu; } else if (document.all) { // IE method: mPointer = document.all.theMenu; } else { // NS 5+ method: mPointer = document.getElementById("theMenu"); }; }; function openMenu() { if (document.layers) { // Netscape 4 accesses things in odd ways... mPointer.visibility = "visible"; } else { // everyone else uses the "style" object: mPointer.style.visibility = "visible"; }; }; function closeMenu() { if (document.layers) { // Netscape 4 accesses things in odd ways... mPointer.visibility = "hidden"; } else { // everyone else uses the "style" object: mPointer.style.visibility = "hidden"; }; clearInterval(closeInterval); }; function menuItemExit() { // start up the timer to close the menu! closeInterval = setInterval("closeMenu()",800); }; function menuItemEnter() { // cancel the timer to close the menu! clearInterval(closeInterval); }; // --> </script> </head> <body onload="setupMenu()"> <a href="#" onclick="return false" onmouseover="openMenu()" onmouseout="menuItemExit()"> <img src="/60-270/images/d0-0.png" alt="Menu" border="0" align="left" id="menuImg" /> </a> <div id="theMenu"> <a href="index.php" onmouseover="menuItemEnter()" onmouseout="menuItemExit()"><img src="/60-270/images/d1-0.png" alt="News" border="0" /></a><br /> <a href="outline.php" onmouseover="menuItemEnter()" onmouseout="menuItemExit()"><img src="/60-270/images/d2-0.png" alt="Outline" border="0" /></a><br /> <a href="schedule.php" onmouseover="menuItemEnter()" onmouseout="menuItemExit()"><img src="/60-270/images/d3-0.png" alt="Schedule" border="0" /></a><br /> <a href="tutorials.php" onmouseover="menuItemEnter()" onmouseout="menuItemExit()"><img src="/60-270/images/d4-0.png" alt="Tutorials" border="0" /></a> </div> </body> </html>

5: A Clock with setInterval()

For this example, we're going to create a clock like the one above, which shows the current time, in 12 hour format (with AM/PM noted), as part of the regular HTML of the web page. This allows us to format the text of the clock with stylesheets in any way we wish, or even have it just blend in with the rest of the page, as in the example above.

It should be noted that this won't work in old browsers such as Netscape 4 - if you need that level of backwards compatibility, your only real solutions are either manipulating images, or text inside of an input tag for a form.

Step 1: The HTML part

Before we can put a clock in a page, we need to have a basic HTML file to put our clock in - in a real example, our clock might be off in some corner of the screen, at the top/bottom/side of the page, or in any one of a number of places - since the code around it doesn't really affect it, we're just going to put the clock all by itself on the page. The only really important part at this point is that we need to choose an ID for our clock - the id attribute can be added to an XHTML tag to uniquely identify it in the page, and our clock will be picked out based on that name. Here's our page so far:

<html> <head> <title>Example Clock</title> </head> <body> Some text! <div id="theClock">The Time!</div> Other content! </body> </html>

Pretty simple - all we have is a div tag with the words "The Time!" inside of it, and an id attribute set to theClock - we haven't even tried to put the time into that block, because that's what our JavaScript is supposed to do.

Step 2: Updating the time

Next, the important step - making the time actually show up in our clock. For this, we actually need one global variable, and two functions - one that does the updating, and one that sets things up for us. We'll do the setup function first:

var clockPointer; function setupClock() { clockPointer = document.getElementById("theClock"); setInterval("runClock()",1000); };

The first thing we do in the code above is create a global variable called clockPointer - since all of our functions and scripts are being created in the head of our page, we can't really put anything in it yet, but it's going to be our way of accessing the div tag that holds our clock.

Next is our setupClock() function - it will be run from the onload DHTML event, which is an attribute on the body tag in our page, that makes sure that the whole page has loaded, and our div tag actually exists before we try to use it. The first line in our function does just that - it sets our clockPointer to point at our div tag based on it's id attribute.

The last thing we do in our setupClock() function is tell the browser that we want to start running a function called runClock() once every 1000 milliseconds (or one second). Since we don't care about being able to stop our clock, we don't need to save the flag that comes back from the setInterval function.

Next, we need to create our runClock() function - this is the part that does all of the work for our clock, and is run once a second to update the time in our div tag. Here's a very simple version of that, which gets the job done, but doesn't look pretty:

function runClock() { var timeNow = new Date(); clockPointer.innerHTML = timeNow.toString(); };

In this version, we're first getting the current date/time with the var timeNow = new Date() command, and displaying it on screen by first turning it into a string (with timeNow.toString()), and then changing the text displayed in our div tag by setting the innerHTML property on it. The problem is, our output will look like this:

Thu Nov 03 2005 18:10:37 GMT-0500 (Eastern Standard Time)

It's a bit long, and a lot more than what we actually wanted - we've got the basic functionality of the clock appearing and updating every second, so the rest of this example is just putting on finishing touches.

Step 3: Showing just the parts you want

The trick to formatting the date we want is to use the methods attached to the Date object. (Which are listed here.) The ones we want will give us just the hours, minutes, and seconds parts of the current time, and we can put them together like this:

function runClock() { var timeNow = new Date(); var outPut = ""; outPut += timeNow.getHours() + ":"; outPut += timeNow.getMinutes() + ":"; outPut += timeNow.getSeconds(); clockPointer.innerHTML = outPut; };

Essentially, we create an empty string, and add each of the hours, minutes, and seconds onto it, with :'s in between them, so that it formats as a date. The results will look something like this. If you watch it for a minute, you'll see that there's a few problems here. The first of course, is that the time that comes out of the .getHours() method is in 24 hour format, and we want to display it in 12 hour format. The second problem is a bit more subtle, and only really appears when there are less than 10 minutes or seconds being displayed - the formatting of our time doesn't take into account the fact that the number will only be one digit!

To fix the problems mentioned above, we can make modifications to our function - mostly by ading in if statements that test for the contitions that cause problems, and fix them if they happen:

function runClock() { var timeNow = new Date(); var outPut = ""; if (timeNow.getHours() > 12) { outPut += (timeNow.getHours() - 12) + ":"; } else { outPut += timeNow.getHours() + ":"; }; if (timeNow.getMinutes() < 10) { outPut += "0"; }; outPut += timeNow.getMinutes() + ":"; if (timeNow.getSeconds() < 10) { outPut += "0"; }; outPut += timeNow.getSeconds(); if (timeNow.getHours() > 12) { outPut += " PM"; } else { outPut += " AM"; }; clockPointer.innerHTML = outPut; };

First, we need to deal with converting our 24 hour format to a 12 hour format. Really, it's quite easy to do - all we have to do is check and see if the number that comes back from .getHours() is more than 12 - if it is, then instead of just adding that number to the string, we subtract 12 from it (thus converting things like 18 to 6).

The problems with single digit seconds and minutes have exactly the same solution as eachother - before we add in the number of minutes/seconds, we check and see if it's less than 10 - if it is, then before we add it, we add in an extra "0" to pad the time.

Last, we want to include an "AM" or "PM" at the end of our time so that people know if it's morning or night - for this we once again check if the hours are more than 12 - if so we add on " PM", otherwise we add " AM". (The space before AM and PM is important! Otherwise it will be stuck on to the seconds with no spacing when it displays!)

After all of our formatting is corrected, our page shoud look like this:

<html> <head> <title>Example Clock</title> <script type="text/javascript"> var clockPointer; function setupClock() { clockPointer = document.getElementById("theClock"); setInterval("runClock()",1000); }; function runClock() { var timeNow = new Date(); var outPut = ""; if (timeNow.getHours() > 12) { outPut += (timeNow.getHours() - 12) + ":"; } else { outPut += timeNow.getHours() + ":"; }; if (timeNow.getMinutes() < 10) { outPut += "0"; }; outPut += timeNow.getMinutes() + ":"; if (timeNow.getSeconds() < 10) { outPut += "0"; }; outPut += timeNow.getSeconds(); if (timeNow.getHours() > 12) { outPut += " PM"; } else { outPut += " AM"; }; clockPointer.innerHTML = outPut; }; </script> </head> <body onload="setupClock()"> Some text! <div id="theClock">The Time!</div> Other content! </body> </html>

Of course, this is a very simplistic looking clock - with a bit of CSS, you can have something a bit nicer, like this.