spacer page banner

Week Three JavaScripting Notes

Tonight we are going to look at the JavaScript event model.

Introduction to Events

Tonight we look at the HTML 4 and 5 specified events to consider our understanding of how to trigger events for event handling in JavaScript.

Events are the beating heart of any JavaScript application. In the context of Web Design and Development, an event occurs whenever something triggers action on behalf of your Web content. The most typical triggers for events are the mouse cursor, mouse buttons, keyboard keys, touch screen touches, and the current time (provided by either the local internal clock or a network clock). On this page we look at what event handling is, what some known problems are and how to write proper cross-browser scripts.

Take a look at any Web page that contains JavaScript in it. In nearly all cases, you will find code associated with available events that triggers your scripts. The reason is very simple. JavaScript was first written expressly to add interactivity to your pages: Your remote audience member does something with their local device while looking at your content and the current page reacts.

To get involved on your behalf, JavaScript needs a way of detecting user actions so that it knows when become active to react. JavaScript also needs to know which functions to execute when an event occurs — functions that do something that you, the web developer, have judged likely to increase the appeal of your pages. This page describes how to write such scripts. Complex script writing isn’t easy, but it is very satisfying work when you see the results you want enthuse your audience.

When the user does something with the mouse or keyboard (or even a more advanced peripheral device like a trackpad or joystick) an event takes place. There are also some events that aren’t directly caused by the user: the load event fires when a page has been fully loaded, for instance.

When the user takes action, he or she causes an event. When your script directs the page to react to this event, interactivity opportunities are born.

In its most ancient form an event handler looks like this. When the user clicks on a link, the event handler is executed and a alert box pops up.

<a href="somewhere.html" onclick="alert('I\'ve been clicked!')">

It is very important to realize that this ancient way of event handling was de facto standardized by Netscape as part of the HTML 4 negotiation process. All other browsers, including Explorer, had to conform to the way Netscape 2 and 3 handled events if they wantedto be HTML 4 complaint and have HTML 4 compliant JavaScript work. Therefore these "ancient" events and event handlers work in all JavaScript browsers.

Modern event models

However, since the introduction of these simple event handlers much has changed. First of all the number of available events for handling has increased. Also, the way of registering event handlers to HTML elements has changed. Events can now be set entirely through JavaScript. No more need for huge numbers of event handlers cluttering up your code, now you can write a simple script that sets all the event handlers for you.

And now browsers provide more information about the event itself. Where was the mouse when an event took place? Was any key pressed while the event occured? Finally, Web browser vendors had to decide what happened when an element and its parent element both had a handler for the same event. Which event should fire first?

A recommended event model appeared on the scene when W3C published the DOM event specification and blessed the W3C’s model, which is loosely based on the original Netscape model but is much more generalized and versatile, is an excellent piece of work — adding lots of new interesting functionalities and solving a lot of problems of older event models.

Browser compatibility problems when using old event models

To be completely backward compatible with very old browsers, we have to take care to execute specific bits of code only in those browsers that understand them. To be safe and avoid ugly visual responses by some browsers, we must first check if the browser supports the methods or properties we want to use.

Older browsers had the unenviable task of deciding which event model to support. Now browsers follow strict standard compliance and support the W3C model. Opera has been more cautious and continues to also support the larger part of both the old Netscape model and the Microsoft model.

It is better not to think about older event models at all, now that almost everyone has a recent enough browser version.

Writing an event handling script

So how do you write an event handling script? First, you register an event handler to your active page.

Registering an event handler

You have to make sure that the browser executes your script whenever the event you’ve chosen takes place.

There are four models for registering event handlers. inline, traditional, W3C and Microsoft.

It’s best to use the traditional model, since it is completely cross–browser compatible and gives much freedom and versatility. To register an event handler:

element.onclick = doSomething;
if (element.captureEvents) element.captureEvents(Event.CLICK);

Now the function doSomething() is registered as the handler of the click event of HTML element element. This means that whenever the user clicks on the registered element, doSomething() is executed.

Accessing the event

When you’ve registered your event handler you start writing the actual script. Usually you want to access the event itself, so you can read out information about the event.

To access the event so that you can read out its properties, always start your event handling function thus:

function doSomething(e) {
	if (!e) var e = window.event
	// e refers to the event
}

Now e refers to the event in all browsers and you can access the event.

Accessing the HTML element

Sometimes you also want to access the HTML element the event took place on. There are two ways for doing this: using the this keyword or using the target/srcElement properties.

The safest way to access the HTML element is by using the this keyword. this doesn’t always refer to the correct HTML element, but in combination with the traditional model it works fine.

function doSomething(e) {
	if (!e) var e = window.event
	// e refers to the event
	// this refers to the HTML element which currently handles the event
	// target/srcElement refer to the HTML element the event originally took place on
}

The target/srcElement properties contain a reference to the HTML element the event originally took place on. Very useful, but when the event is captured or bubbles up the target/srcElement doesn’t change: it’s still the element the event originally took place on. (See the Event properties page for target/srcElement, see the this page for the this keyword)

Reading out properties

As to reading out interesting event properties, this is the area with the worst browser incompatibilities. Study the event compatibility tables and write your own script to read out the information you need.

Be sure to always use the most detailed object detection possible. First check if each property exists, then read out its value. For instance:

function doSomething(e) {
	if (!e) var e = window.event
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
}

Now code contains the pressed key in all browsers.

Event order

Finally, you have to decide whether you want the events to bubble up. If you don’t want that to happen, stop the propagation of the event.

function doSomething(e) {
	if (!e) var e = window.event
	// handle event
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

Writing the script

Let's look at how we can add our own event triggers to DOM elments.

Now you can start actually writing the event handling script. Use the information the previous snippets of code give you to decide what actually happened when the event took place and how your script should react to it. Remember: keep the interaction logical or your users won’t understand what’s happening.

An example of how events were first coded

Now that JavaScript is the recommended scripting language for all browser event handling, the code is simpler:

<html>
<head>
<title>Example 1</title>
</head>
<body>
<a href="http://bdcampbell.net/xml/" onMouseOver="document.myimage.src='http://bdcampbell.net/javascript/hover.png'"
onMouseOut="document.myimage.src='http://bdcampbell.net/javascript/normal.png'">
<img name="myimage"
src="http://bdcampbell.net/javascript/normal.png"></a>
</body>
</html>

A second example (you can download the example here):

<html>
<head>
<script language="JavaScript">
// check name field
function checkName() {
    // if empty, pop up alert
    if (document.forms[0].name.value == "") {
        alert("Please enter a valid name");
        return false;
    } else {
        return true;
    }
}

// check email field
function checkEmail() {
    var flag;
    var str = document.forms[0].email.value;
    // regular expression to match email addresses
    var pattern = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/;
    var flag = pattern.test(str);
    if(!flag) {
        alert ("Please enter a valid email address");
        return false;
    } else {
        return true;
    }
}
// function to check all form data
function checkForm() {
    if (checkName() && checkEmail()) {
        return true;
    } else {
        return false;
    }
}
</script>
</head>
<body>
<form action="#" method="post" onsubmit="checkEmail()">
Please enter your name. <br> <input type="text" name="name" onblur="checkName()"> <p> Please
enter your email address. <br> <input type="text" name="email"
size="25" onblur="checkEmail()"> <br> <input type="submit" value="Hit me!"> </form>
</body>
</html>

You can also use the onFocus and onBlur handlers to perform actions when the user tabs into or out of a form field.

JQuery Examples for Week Three

Build this Web document in a text editor.

Notes from our lecture together follow below, after presenting the visual representation of the document's main content for your verification.

Use the buttons to the left, in the examples, to run jQuery code on the structural markup below.
Showing the code for each example will display the jQuery code required to make the changes to the structural markup happen.
The code is explained in the context of the whole event handling process below.

Here is some HTML code we can change based on using JQuery event handlers.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

The code behind the interactive JQuery document you downloaded is reproduced below. I have added explanations to supplement the explanations given in class.
Be sure to download the JQuery JavaScript Library, name it jquery.js, and place it in the same folder where you placed the downloaded code.
The JQuery library calls will not work without it.

The code in orange is the HTML element that will make the JQuery library available to the page.
The code in blue is the JQuery control block that controls code that should only become active once the Web page has loaded in the Web browser.
Read more about that here.
The code in dark green shows you an example of declaring your own click event on all A elements in your page.
The code in bright red shows you an example of creating your own function to handle events generated from the original Netscape 2 event model.
The code in magenta shows you an example of creating your own JQuery event handler in order to respond to an interactive visual control that has the relevant class attribute.
The code in purple is the actual JQuery event handler detail for the response you want to provide to the triggering of the event associated with the handler.

In order for us to get more sophisticated with JQuery coding, we will be studying these event model examples closely. Important things to realize (and
play with in order to confirm your understanding):

All events in these examples have a visual component with which the Web page audience can interact to make change happen in our presentation.
The visual components all exist within HTML tags that are HTML 4 compliant. We will look at writing code where we can create Web event controls
from within our JavaScript (with or without our JQuery library). We will use the <b>document.write()</b> method to write without the JQuery library
and we will use the <b>$('body').append('<h1>test</h1>');</b> method to write with the JQuery library.

All event handler content can be substituted in any of the three places where it has been used in this downloaded document. You can mix and match
handlers from all six of the examples from the tutorial (just use the show code link to see the code that needs to copied and pasted into your JQuery code).

An easy way to anticipate the use of the JQuery library is through the visual sighting of the $ symbol that precedes much of the JQuery-compliant syntax.
Do try and figure out how the purple handling routines provide the visual changes. The better you get at that, the more relaxed you'll be using examples
you find in tutorials and in documents on the Web in general.

Read about all the built-in HTML element attributes that can initiate (trigger) events and change the HTML in the downloaded document to verify that
they work (with or without JQuery in the handler). Our first six examples in class together (four via the second week lecture and workbook and the two
above this JQuery examples section) did not use JQuery at all. We don't have to download extra .js files if we don't use one or more external libraries.
You can download Version 1.7.2 of jquery.js.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html lang="en">
 <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js" type="text/javascript"></script>
   <script type="text/javascript">
     $(document).ready(function(){   
       $("input.a").click(function(event){
         $("div.contentToChange p.firstparagraph:visible").slideUp("slow");
       });

       $("input.b").click(function(event){
         $("div.contentToChange p.firstparagraph:hidden").slideDown("slow");
       });

       (function ($) {
          $.changeParagraph = function() {
            $("p.fifthparagraph").addClass("changeP");
          }
        })(jQuery);

        $("input.buttonCAdd").click(function(){
          $("div.contentToChange").find("p").not(".alert").append("<strong class=\"addedtext\"> This text was just appended to this paragraph</strong>")
        });
      });
   </script>
   <style type="text/css">
	.changeP{
		color: #FFFFFF;
		border: 2px solid #CC6633;
		width: 150px;
		background-color: #CC6633;
		padding:10px;
		line-height:1.4em;
	}
	.alert {
		font-weight: bold;
		color: #FFFFFF;
		background-color: #FF0000;
		padding: 10px;
		text-transform:uppercase;
	}
	
	.addedtext{
	color:#FF0000;
	}
	
	pre {
	display: none;
	}
   </style>
</head>
<body>
   <button type="button" id="btn" onClick="$.changeParagraph()">Click Me!</button>
   <input type="button" value="Hide" class="a" />
   <input type="button" value="Show" class="b" />
   <div style="width:50%;background:#F5F5F5;padding:5px" class="contentToChange">
      <p class="alert">Here is some HTML code we can change based on using 
      JQuery event handlers.</p> 
      <p class="firstparagraph">Lorem ipsum <em>dolor</em> sit 
      amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh
       euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat 
       <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam
       </em>, quis nostrud exerci <strong>tation</strong> 
       ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
      <p class="secondparagraph">Duis autem vel eum iriure dolor in hendrerit 
      in vulputate velit esse <strong>molestie</strong> consequat, vel 
      illum <strong>dolore</strong> eu feugiat nulla facilisis at vero 
      eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril 
      delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit 
      amet, consectetuer <strong>adipiscing</strong> elit, sed diam 
      nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
      <p class="thirdparagraph">Ut wisi enim ad minim veniam, quis nostrud 
      exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea <em>
      commodo</em> consequat. Duis autem vel eum iriure dolor in hendrerit in 
      <em>vulputate</em> velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim 
      qui blandit praesent luptatum zzril delenit augue duis dolore te 
      <strong>feugait</strong> nulla facilisi.</p>
      <p class="fourthparagraph">Lorem ipsum dolor sit amet, consectetuer 
      adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore 
      magna aliquam erat volutpat. Ut wisi enim ad minim veniam, <strong>quis
      </strong> nostrud exerci tation ullamcorper suscipit lobortis nisl ut 
      aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in <em>
      hendrerit</em> in vulputate velit <em>esse</em> molestie 
      consequat, vel illum dolore eu feugiat nulla <strong>facilisis
      </strong> at vero eros et accumsan et <em>iusto</em> odio 
      dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te 
      <strong>feugait</strong> nulla facilisi. Lorem ipsum dolor sit 
      amet, consectetuer adipiscing elit, sed diam nonummy nibh <strong>
      euismod</strong> tincidunt ut laoreet <em>dolore</em> magna 
      aliquam erat volutpat.</p>
      <p class="fifthparagraph">Lorem ipsum <em>dolor</em> sit 
      amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nib 
      euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat 
      <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam
      </em>, quis nostrud exerci <strong>tation</strong> 
      ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
      <p class="sixthparagraph">Duis autem vel eum iriure dolor in hendrerit 
      in vulputate velit esse <strong>molestie</strong> consequat, vel 
      illum <strong>dolore</strong> eu feugiat nulla facilisis at vero 
      eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril 
      delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit 
      amet, consectetuer <strong>adipiscing</strong> elit, sed diam 
      nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
   </div>
</body>
</html>
 

Diagramming the above JQuery example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
	$("a").click(function(event) {
		function($("div.contentToChange p").length);
	});
	(function($) {
		$.changeParagraph = function() {
			$("p.fifthparagraph").addClass("changeP");
		}
	}) (jQuery);
	$("input.buttonCAdd").click(function() {
		$("div.contentToChange").find("p").not(".alert").append("<strong class=\"addedtext\"> This text was just appended to this paragraph</strong>")
	});
});
</script>
<style type="text/css">
.changeP {
	color: #FFFFFF;
	border: 2px solid #CC6633;
	width: 150px;
	background-color: #CC6633;
	padding:10px;
	line-height:1.4em;
}
.alert {
	font-weight: bold;
	color: #FFFFFF;
	background-color: #FF0000;
	padding: 10px;
	text-transform:uppercase;
}
.addedtext{
	color:#FF0000;
}
pre {
	display: none;
}
</style>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<button type="button" id="btn" onClick="$.changeParagraph()">Click Me!</button>
<input type="button" value="Add" class="buttonCAdd" />
<div style="width:50%;background:#F5F5F5;padding:5px" class="contentToChange">