|
||||||||
Week Three JavaScripting NotesTonight we are going to look at the JavaScript event model. Introduction to EventsTonight 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 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 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. 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 modelsTo 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 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 scriptLet's look at how we can add our own event triggers to DOM elments.
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 ThreeBuild 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. 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="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> |
||||||||
<!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">