//Cyber Battlefield/Client Side Scripting – Event Driven

Big Picture

In this lesson we will learn to write scripts for web pages that are event driven, meaning that the script executes when some event occurs. These scripts need to make use of new DOM facilities like document.getElementById( ... ) to make changes at given locations in a web page.

Terminology

Having JavaScript execute based on an event occurring is great, but we need a way to identify specific HTML Elements within the HTML Document so our event driven code can modify specific content within the document. For this we can use the HTML Id Attribute.

id [HTML Attribute]
Used to identify an HTML Element within the HTML Document.
The id attribute can be specified for any HTML Element.
Ids are supposed to be unique within the document.
The value assigned has to be at least one character in length, and cannot contain spaces.

Mouse Events

The events that we're most used to in web-browsing are mouse-related — starting, of course, with the click. Any element can be given an onclick attribute whose value is a chunk of JavaScript code to be executed whenever the mouse is clicked within that element. Here's a nice example (Note that document.body gives you the DOM body element without the fuss of having to give it an id and go through calling document.getElementById(...)):
Interactive content Code that makes it happen

Clicking anywhere within the bold text causes the background to go red! Refresh the page to return sanity.
Clicking anywhere
<b onclick='document.body.style.background="#ff0000"'>within the bold text</b>
causes the background to go red!  Refresh the page to return sanity.
There are actually a number of mouse events that are scriptable this way via the following attributes: Exercise: add the word "disclaimer" to the bottom of your web page (in bold) and make it so that when you click on the word, an alert box pops up saying
The opinions expressed in this web page are solely those of the author and do not necessarily reflect the opinions of USNA, the Navy, the DoD, the Federal Government, the United Nations or the Galactic Federation.
It should work like this: disclaimer. ← Click on This!

Using Events for Redirection and Content Changes