1 / 30

CSC 3084: Web Development and Programming

CSC 3084: Web Development and Programming. Chapter 6: How to Script the DOM with JavaScript. Chapter Overview. By the end of this chapter, you should be able to : Use the properties and methods of the Node, Document, and Element interfaces in your JavaScript applications.

cher
Télécharger la présentation

CSC 3084: Web Development and Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSC 3084:Web Development and Programming Chapter 6: How to Script the DOM with JavaScript

  2. Chapter Overview • By the end of this chapter, you should be able to: • Use the properties and methods of the Node, Document, and Element interfaces in your JavaScript applications. • Cancel the default action of an event. • Preload the images for an application. • Use one-time and interval timers. • Use JavaScript to develop common DOM scripting applications.

  3. The Code for a Web Page <!DOCTYPE html> <html> <head> <title>Join Email List</title> </head> <body> <h1>Please join our email list</h1> <form id="email_form" name="email_form" action="join.html" method="get"> <label for="email_address">Email Address:</label> <input type="text" id="email_address"> <span id="email_error">*</span><br> </form> </body> </html>

  4. The DOM for the Web Page

  5. Commonly-used DOM Nodes • We will explore these as we go: • Document Root node of the DOM. • Element An element in the web page. It can have element, Text and Comment nodes as child nodes. • Attr An attribute of an element. It can have a Text node as a child node. • Text The text for an element or attribute. It can’t have a child node. • The properties and attributes available for use in DOM scripting comprise the DOM Core specification.

  6. Some Properties of the Node Interface • In JavaScript, interface simply means the properties and methods for an object nodeValueThe text of a node. parentNode Parent node of the current node. childNodesAn array of child nodes of the current node firstChild First child of the current node. lastChild Last child of the current node nextElementSiblingReturns a Node object for the next sibling.

  7. Nodes Example <body> <h1>Please join our email list</h1> <form id="email_form" name="email_form" action="join.html" method="get"> <label for="email_address">Email Address:</label> <input type="text" id="email_address"> <span id="email_error">*</span><br> <label>&nbsp;</label> <input type="button" id="join_list" value="Join our List"> </form> </body>

  8. Nodes Example (cont.) • How to get the text of an HTML element : varerrorText = $("email_error").firstChild.nodeValue; • How to set the text of an HTML element: $("email_error").firstChild.nodeValue = "Entry is invalid."; • How to set the text for the span tag to an empty string without using its id: $("email_address").nextElementSibling .firstChild.nodeValue = "";

  9. Methods of the Document and Element Interfaces • getElementsByTagName(tagName) • Returns an array of all Element objects descended from the element that have a tag that match the specified tag. • getElementsByName(name) • Returns an array of all Element objects descended from the element that have a name attribute that match the specified name. • getElementsByClassName(classNames) • Returns an array of all Element objects descended from the element that have a class attribute with a name or names that match the parameter.

  10. Methods of the Element Interface • hasAttribute(name) • Returns true if the Element has the attribute specified in the name. • getAttribute(name) • Returns the value of the attribute specified in the parameter or an empty string if the attribute was not set. • setAttribute(name, value) • Sets the attribute specified in the parameter to the given value. If the attribute doesn’t yet exist, it is created too. • removeAttribute(name) • Removes the attribute specified in the parameter

  11. How to Create Arrays of Elements • How to create an array of all <a> tags: var links = document.getElementsByTagName("a"); • How to create an array of all li tags within a ul element named image_list: • var list = document.getElementById("image_list"); • var items = list.getElementsByTagName("li");

  12. How to Work with Attributes • How to test for and get an attribute: var list = document.getElementById("image_list"); if ( list.hasAttribute("class") ) { varclassAttribute= list.getAttribute("class")); } • How to set an attribute: varimage = document.getElementById("image_list"); image.setAttribute("class", "open"); • How to remove an attribute: var list = document.getElementById("image_list"); list.removeAttribute("class");

  13. The FAQs Application • See JS Textbook Files\book_apps\ch06\faqs_1\index.html • So what’s the deal with the this keyword? • It’s similar to this in Java, but only superficially. • The reference to thisin the code (i.e., h2 = this;) ensures that a distinct event handler is created for and assigned to each h2 element. • If we had done h2 = h2Node instead, then h2 for every handler would have referred to the last h2 element in the DOM because the last h2 element is the final value of the h2 variable when the for-loop finishes. You will verify this when we do an exercise later.

  14. Version 2 of the FAQs Application • See JS Textbook Files\book_apps\ch06\faqs_1\index.html • This version is simpler, but has the exact same functionality. • No classes need to be assigned to the h2 elements or div elements in the HTML because of how the JavaScript has been rewritten. • Rather than changing class attribute values, the JavaScript adds or removes attributes. • But the real benefit of this new version is that the HTML is simpler and cleaner.

  15. Navigation Guidelines for Usability • Underlined text is always a link. • A small symbol in front of a text phrase is clickable. • Images that are close to short text phrases are clickable. • Buttons should look like buttons and should always be clickable. • How the FAQs usability can be improved: • Highlight the heading when it has the focus or when the mouse hovers over it.

  16. Guidelines for Accessibility • For the visually-impaired: • All of the essential information should be presented in text that’s easy to read because some users may not be able to read the text that’s in images. • For the motor-impaired: • All of the essential content and features should be accessible with the keyboard because some users may not be able to use a mouse.

  17. How the FAQs Application’s Accessibility can be Improved • Make the headings links (using <a> tags) so the user can use the Tab key to move from one to the next. • Move the cursor to the first heading when the page is loaded. • Highlight the heading when it has the focus or the mouse is hovered over it. • Let the user activate the click event of a heading by pressing the Enter key when the heading has the focus. • See JS Textbook Files\book_apps\ch06\faqs_links\index.html

  18. Common Default Actions for click Events Tag Default Action a Load the page or go to the placeholder in the href attribute. input Submit the form if the type attribute is set to submit. input Reset the form if the type attribute is set to reset. button Submit the form if the type attribute is set to submit. button Reset the form if the type attribute is set to reset.

  19. Canceling the Default Action • DOM-compliant code: vareventHandler = function (evt) { evt.preventDefault(); } • IE code: (why? because IE stinks, that’s why) vareventHandler = function () { varevt = window.event; evt.returnValue = false; }

  20. Browser-compatible Code that Cancels the Default Action vareventHandler = function (evt) { // If the event object is not sent, get it if (!evt) { evt = window.event; ) // for IE // Cancel the default action if (evt.preventDefault) { evt.preventDefault(); // for most browsers } else { evt.returnValue = false; // for IE } }

  21. Preloading Images • When an application preloads images it loads all of the images that it’s going to need when the page loads and caches them in the web browser. • If images are not preloaded, then they are retrieved from the web server on demand, which can cause rendering delays. • Pre-loading occurs in a two-step process: • Use the new keyword to create an Image object. • When you set the src attribute of this object, the web browser preloads the image identified by that attribute.

  22. How to Create and Preload an Image Object • How to create an Image object: var image = new Image(); • How to preload an image in an Image object: image.src = "image_name.jpg";

  23. How to Preload All Images via the hrefAttributes of <a> Tags varlinks = document.getElementsByTagName("a"); vari, link, image; for ( i = 0; i < links.length; i++ ) { link = links[i]; image = new Image(); image.src = link.href; }

  24. Image Swap Application • See JS Textbook Files\book_apps\ch06\image_swap\index.html • In image_swap.js, you will notice that the default event handler for clicking on a link has been canceled and replaced with new code • The new handler changes the main img element to show the desired image and changes the h2 element containing the caption to the desired caption text. • After the new event handler has been set up you can see that the image is also preloaded.

  25. How to Use Timers • A timer lets you execute function after a specified period of time has passed • In JavaScript, you can have a timer call its function only once or periodically • See JS Textbook Files\book_apps\ch06\faqs_timers\index.html • This example features both kinds of timers • Two methods for working with a one-time timer: setTimeout(function, delayTime) // creates a timer clearTimeout (timer) // cancels a timer

  26. The JavaScript that Hides the Heading // declare a global variable for the timer var timer; // create a timer that calls the hideMessage function window.onload = function () { timer = setTimeout(hideMessage, 5000); } // create the function that the timer calls varhideMessage = function () { $("startup_message").setAttribute("class", "closed"); clearTimeout(timer); }

  27. How to Embed the timer Function in the setTimeout Method • This is an alternate way of providing the function for the timer: window.onload = function () { var timer = setTimeout( function () { // the start of the first parameter $("startup_message").setAttribute("class", "closed"); clearTimeout(timer); }, 5000); // the second parameter }

  28. How to Use Interval Timers • Two methods for working with an interval timer: setInterval(function, intervalTime) clearInterval(timer)

  29. The JavaScript that Updates the Counter window.onload = function () { // create a timer that calls // the updateCounter function every second var counter = 0; var timer = setInterval( function () { // the start of the first parameter counter++; document.getElementById( "counter").firstChild.nodeValue= counter; }, 1000 ); // the second parameter }

  30. A Slide Show Application • It’s a simple program with no controls, but it could serve as the starting point for a real slide show program • See JS Textbook Files\book_apps\ch06\slide_show\index.html

More Related