|
||||||||
Week Three JavaScripting NotesTonight we are going to look at the JavaScript event model. Introduction to EventsTonight we look at the HTML 4 specified events to consider our understanding of how to trigger events for event handling in JavaScript. The following page content has been modified from a base found on the Quirksmode website. Tonight we look 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, 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 to spring into action 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. These pages describe the best way to write such scripts. Complex script writing isn’t easy, but it is very satisfying work when you see the results you want enthuse a targeted reader. 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 The JavaScript interpreter associated with a Web browser can detect some of these events. Since 1995, when Netscape released their Netscape 2 Web browser onwards it has been possible to associate an event handler to certain HTML elements — starting humbly with anchor tags and form fields in the early days. The event handler waits until a managed event, for instance a Web mouse button click on a link, takes place. When the manged event happens, the JavaScript intterpreter handles the event by executing the respective JavaScript you have defined. 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. History of event handlingThe best scripts are those that react intuitively to something the user does. Netscape released its Version 2 browser which supported JavaScript, it also supported handling some useful events. Netscape modelNetscape 2 supported popular mouseover and mouseout events which quickly became famous because of the legendary mouseover effect that swapped images in during onMouseOver events and swapped them back out during onMouseOut. With a Netscape 2 browser it became possible to see if the user submits or resets a form, such that client–side form validation became possible. The browser could also detect if a form field received or lost focus or if a Web page had finished loading or started unloading. Although by present standards this is very basic behavior, at that time it was a revolutionary extension of the possibilities of Web pages. True interaction became possible because you could react to user actions. In its most ancient form an event handler looks like this. When the user clicks on this link, the event handler is executed and the alert 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 modelsHowever, 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. Fourth generation 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? Much of the fourth generation functionality was added at the height of the Browser Wars. As a result, Netscape and Microsoft made a distinct point of creating totally incompatible event models. More recently a third model has appeared on the scene when W3C published a DOM event specification. Despite one serious flaw, the W3C’s model, which is loosely based on the old Netscape model but 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. The existence of three different yet popular event models has resulted in a situation where event handling doesn’t reliably work the same way in all browsers. Browser compatibility problemsThere we go again. As with issues implementing Dynamic HTML (DHTML) effects, the W3C DOM, or other advanced scripting techniques, 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. But an overly simple code branch like
if (Netscape) {
use Netscape model
}
else if (Explorer) {
use Microsoft model
}
is only a first approximation of a solution since it leaves out the minor browsers. The most recent ones can handle a fair amount of modern event handling, unless your script in its infinite wisdom decides that the minor browsers should not be allowed to even try to run the code because they are not Netscape or Explorer. All minor browsers have had the unenviable task of deciding which event model to support. Konqueror/Safari, as always, has opted for strict standard compliance and supports the W3C model. Opera and iCab have been more cautious and support the larger part of both the old Netscape model and the Microsoft model. Many if not most of us learn the event model implementations by trial and error. But a relatively unknown browser might support the Microsoft way of accessing an event, while the actual event properties are a mix of the W3C and the old Netscape model. This should be no problem, after all the browser follows well known patterns in its own way. Your scripts should be ready for it. Don’t use that browser detectFirst of all never use a browser detect approach. This approach is old from Netscape 2 days and almost any script that uses Secondly, don’t confuse DHTML object detection with event object detection. When writing DHTML we commonly check for DOM support by asking, for instance, But DHTML and event handling have different browser compatibility patterns. For instance,
Opera 6 supports parts of the W3C DOM but not the W3C event model.
Therefore DHTML object checking would execute the wrong event code branch in Opera. So scripts using
The right questionsThen what are we to do? The names of the some event properties cause many of the worst event handling problems. If we use a lot of browser-specific object detections in this area, we solve 99% of the browser incompatibilities. Finding the current mouse position is very hard, while accessing other bits of information is simpler. Furthermore, it is better not to think about three overall event models at all. Instead, we have to understand four event registration models, two event accessing models and two event orders. See also this quick event compatibility tables for a broad overview of event handling and browser compatibility. Although this event model confusion sounds terribly complicated, it isn’t. When you discover the differences and start to make sense of them, you begin to truly understand event handling at a deeper level that becomes very useful over time. Event handling coding is all about asking the right questions. Instead of always asking, “How should I write an event handling script?”, you can start by asking more specific questions that have specific answers:
All questions above will be treated on separate pages that give background information and the nuts and bolts of event handling. The trick of writing cross–browser event handling scripts is not to use an overall event model check but to answer all these questions separately. You’ll find that you need to worry about browser compatibility mainly when reading out event properties. First choose an event registration model, then make sure the event is accessed by all browsers, then read out the correct properties and then solve event order problems — if any occur. Thus you can solve each compatibility problem separately and ensure your code runs in all browsers that support advanced event handling. Writing an event handling scriptSo how do you write an event handling script? First, you register an event handler to your active page. Registering an event handlerYou 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 Accessing the eventWhen 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 Accessing the HTML elementSometimes you also want to access the HTML element the event took place on. There are
two ways for doing this: using the The safest way to access the HTML element is by using the
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 Reading out propertiesAs 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 Event orderFinally, 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 scriptNow 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 (you can download a similar example here):
<a href="http://somewhere" onMouseOver="popeye()"
onMouseOut="olive()"><img name="myimage" src="normal.jpg">
</a>
<script language="JavaScript">
function popeye() {
document.myimage.src='hover.jpg';
}
function olive()
{
document.myimage.src='normal.jpg';
}
</script>
An alternative way of writing the same event handler:
<a href="http://somewhere" onMouseOver="document.myimage.src='hover.jpg'" A second example (you can download the example here): <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 ThreeDownload this Web document, study it, and then experiment with the example JQuery-based event handlers provided in the tutorial.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. 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 All events in these examples have a visual component with which the Web page audience can interact to make change happen in our presentation. 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 <!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="jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ $("a").click(function(event){ alert($("div.contentToChange p").size()); }); (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"> <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>
|
||||||||