Client-side scripting with JavaScript

Derek Bridge

Department of Computer Science,
University College Cork

Client-side scripting with JavaScript




Client-side JavaScript

Dynamic HTML (DHTML)

[The trinity of web standards for DHTML.]

Client-side JavaScript: simple example

Event-driven programming

  • Many programs nowadays use event-driven programming: when an event occurs, the system runs a function to handle the event
  • In client-side JavaScript, events include:
    • when the document has finished loading
    • when the user clicks on a hyperlink
    • when the user clicks on a button
    • when the user moves the mouse into or out of a certain region of the screen
    • ...
  • One way this is done is by using special attributes on (X)HTML elements, e.g. onload, onclick, onmouseover, onmouseout

Client-side JavaScript: image rollovers

    To change an image when the mouse moves over it:
    <img src="frown.jpg"
    onmouseout="this.src='frown.jpg'" />
  • See rollover1.html

Unobtrusive client-side JavaScript

Recently, there has been a concern for writing scripts that are unobtrusive:

  • Scripts should not make web pages less usable (e.g. scripts that automatically set this page as your home page)
  • Scripts should not make web pages less accessible (e.g. pop-ups, or visual effects with no text alternative)
  • Scripts should degrade gracefully, i.e.
    • the web page is still usable by someone who has disabled JavaScript
    • the web page is still usable by all versions of all browsers
  • Like CSS stylesheets, scripts should be in separate, external files, with a link to the file, rather than intermingled with the (X)HTML. Why?

Client-side JavaScript: unobtrusive image rollovers

rollover2.html: the XHTML (xml prolog and DOCTYPE omitted)

<html xmlns="" xml:lang="en" lang="en">
  <title>Make me smile</title>
  <script type="text/javascript" src="rollover2.js">
 <img id="face" src="frown.jpg" />

Client-side JavaScript: unobtrusive image rollovers

The JavaScript:

if ( window.addEventListener )
	window.addEventListener("load", init, false);
else if ( window.attachEvent )
	window.attachEvent("onload", init);

function init()
	(new Image()).src = 'smile.jpg';
	document.getElementById("face").onmouseover = make_it_smile;
	document.getElementById("face").onmouseout = make_it_frown;

function make_it_smile()
	document.getElementById("face").src = 'smile.jpg';

function make_it_frown()
	document.getElementById("face").src = 'frown.jpg';

Client-side JavaScript: unobtrusive image rollovers

rollover3.html: In fact, for image rollovers, forget JavaScript!
CSS can do it:

	display: block;
	width: 500px;
	height: 500px;
	background: url('frown.jpg') top left no-repeat;

	background: url('smile.jpg') top left no-repeat;

Client-side JavaScript: so what would you use it for?

All the following can be done client-side, at the user's request: