ABSTRACT



IS 360 JAVASCRIPT DOM AND FORMS LABEKEDAHLABSTRACTIn this lab, you will:Work with HTML5 and legacy widgets to get user input and create buttons.Continue to call the getElementById() method.Call the getElementsByTagName() method to select multiple elements and perform operations on them.Dynamically change styles using the querySelectorAll() method.Navigate nodes using the childNodes property and the nodeType property.Handle events such as onMouseOver and onMouseOut.Work with HTML 5 input widgetsContinue to use the Google DebuggerThere are a group of properties that contain references to other nodes in the hierarchy. All of these property return null if there is no node or node list.The childNodes property returns a collection (NodeList) of the children belonging to this node. \n the firstChild property returns the first child belonging to this node.\n The lastChild property returns the last child of this node. nextSibling returns the next node in the tree. \n The previousSibling property returns the previous node in the tree. The parentNode property returns the parent of this node. The nodeType property returns the type of the node. Node types appear in the following table.Iterating a List of NodesIn addition to the item property a collection has a property named length. Together, you use these to properties with a for loop to iterate through each node, and then do something with it. The following code template shows how to enumerate a list of nodes[code]The loop’s counter is initialized to zero. \n The counter is incremented by 1 each time through the loop. Each time through the loop the counter is compared to the length. This comparison causes the loop to exit after all of the nodes have been examined. The statement in the loop gets a reference to an element.Using CSS Styles with a NodeEach node has several properties. The style property allows you get or set the various styles associated with the attribute. Generally, the JavaScript file names work similar to CSS names. The dashes are removed. The names are replaced with CamelCase names. The values are exactly the same as the CSS values. They are expressed as quoted strings. The following code segment illustrates how to set the style property.[CODE]HANDS-ON EXERCISE: Displaying and hiding list elements using getElementsByTagName and getElementById():In this exercise, you will create multiple <li> elements. Then, you will create buttons to display and hide these elements. This technique of displaying and hiding elements is useful when creating a page intended to operate in summary and detail mode. Here, you will be using the same techniques presented in class.Create an emptyUsing GetElementByClassNameIn the same document you have been editing, enter the following HTML code immediately after the second<span> tag that you created in the preceding steps. Here, you are just creating and unordered list and list items within the unordered list. The getElementById() method of the document object is used to get a reference to an element having a particular value for the id attribute. A single element is returned by the method call because id attribute values must be unique in a document. If there is no element having the specified value for the id element, then the method call will return null. As usual, JavaScript errors will fail passively. That is, the browser will not usually display an error message, or cause the rendering process to fail.In this exercise, you will create a document with a single <span> tag having a value for its id attribute. The script that you write will get a reference to this element and store the current date as the element’s innerHTML. Insert a <span> tag immediately after the <body> tag as follows: Now insert the script at the end of the document, just before the ending </body> tag. Note that this script must appear after the <span> tag. If it does not, the browser will have not yet read the tag, and it will not exist. Another possibility would be to put this code in a function and call the function after the document object has loaded. Thus, nothing will happen as JavaScript fails passively:Run the program displaying it in the default browser. The current date should appear as shown in the following figure:If your program does not display the date, check that you have properly capitalized the name of the getElementById() method, the ID Names, and the Date() method.In these next steps, you will try a similar task on your own. You will create a second <span> tag. Then you will create a second script that will get the name of the browser and display a value indicating whether JavaScript is enabled or not. You will need to use the following code snippet to get the browser name and to determine whether JavaScript is enabled or not. Recall that the navigator object references the browser, and the appName property gets the name of the browser. The javaEnabled property returns a Boolean value indicating whether JavaScript is enabled or not. The following code segment shows the statement fragment:navigator.appName + " " + " Java Enabled " + navigator.javaEnabled();Create another span tag after the one that you just created. Set the id attribute to spnNav.Create a second script after the first one at the end of the document. Call the getElementById method as before to get a reference to the span tag named spnNav. Change the name of the argument, as necessary.Write the above statement to get the name of the browser and store the result in the innerHTML property of the span tag.Test the application. The browser name and the result of the javaEnabled method should appear in the browser window.HANDS-ON EXERCISE: Create the following buttons. Enter this code following the unordered list that you just created.Note in the above code, that you are referencing two event handlers named Collapse() and Expand(). Each of these event handlers will be called when the button is clicked (the onclick event). You will create these procedures (event handlers) in the next set of steps. Each of these event handlers will execute, when the user clicks the respective button. Again, use care to make sure that the onclick event is all lower case. Make sure that the case of the Collapse and Expand procedures is the same.Next, write the following code in the <head> block to create the two procedures that will operate has event handlers. Recall that functions declared in a <head> block are not executed until they are explicitly called. Code outside a function is executed as it is encountered.The following list describes the operation of the above two event handlers:The functions are named Collapse() and Expand(), respectively. The procedures do not accept any arguments. They also do not return a value.The first statement in each procedure gets all elements in the document having a tag named <li>. That is, all list items will be selected, even if there are multiple lists. The result is stored in the variable named elements. Since multiple elements might be <li> elements, the method returns an array or list of element references. The for loop enumerates the array as discussed in class. The syntax of a for loop is described at variable x is initialized to 0. (x = 0) Each time through the loop, elements.length is tested. elements.length returns the number of elements in the array. All arrays support a property named length, which returns the number of elements in the array. Thus, when x is equal to the array size, the loop exits. Each time through the loop, the variable x is incremented by one. (x++)The statement in the loop selects the xth element from the array (elements[x]). The next part of the statement sets a CSS style. The final part of the statement sets the display property of the selected element. The display property is set to either none (making the element invisible) or block (making the element visible and operate as a block tag).Now run the program. The unordered list should appear. Click each of the two buttons. As you do, the list should become visible and invisible as shown in the following two figures:Next, you will try a similar task on your own. It’s possible to get all elements belonging to a particular CSS class by calling the getElementsByClassName() method. The method takes one argument, the name of the CSS class. Thus, calling this method allows you to get a list (array) of elements that belong to the same CSS class.Create a second unordered list immediately after the first list and buttons that you just created. Note that each of the above list items belongs to the same class (hideList).Create two additional buttons as follows: Create event handlers, as necessary, in the <head> section to get all items belonging to the class named hideList. These event handlers should be named CollapseC and ExpandC. These event handlers should work like the ones that you just created. Use the following statement as a hint to get you started:The for loop that you write should be about the same as the first two loops that you wrote.Run the program again. When you click the two new buttons, only the list items belonging to the defined class should be displayed and hidden.Click the original buttons. All of the list items are made visible and invisible. This occurs because one group of procedures displays or hides all list items. The others display and hide only those list items belonging to a specific class.HANDS-ON EXERCISE: Navigating Child Nodes and Handling EventsIn this exercise, you will again navigate through the DOM so as to display and hide nodes. However, this time, you will further refine the selection criteria as follows:Every node supports a property named childNodes. This property returns all of the immediate children of the node selected. The property returns a list of nodes, just as the getElementsByTagName() method returns a list of node. Each individual node supports a number of properties:The tagName property contains the name of the tag (for element notes).The nodeType property contains the type of node. Node types are always one of the following:Element nodes have a value of 1.Attribute nodes have a value of 2.Text nodes have a value of ment nodes have a value of 8.In this hands-on exercise, you will create a new document with multiple articles. As the user moves the mouse over and off of each article, the child contents will be displayed and hidden, respectively. You will do this by displaying and hiding nodes.Create a new document named NavigateArticles.htm.Enter the following content. The structure is important to the exercise. The content (yip, yip) is not.Note the following about the above content that you created.Each article has an id defined, but it is not used.Both articles handle the events named onmouseover and onmouseout. Recall that onmouseover fires when the mouse hovers over the element, and onmouseout fires when the mouse is moved off of the element. Note that the event handlers are the same for both <article> tags.Each event handler accepts one argument. The argument is named this. I strongly suggest that you visit the following URL for a comprehensive reference to the this keyword. ()Each article contains two child elements named <h1> and <p>. The code that you will write in a moment will display and hide these elements.Next, you will create the two event handlers. In the <head> block create the necessary script tag and the corresponding event handlers.The following list describes the code that you just created. Both of the procedures work nearly the same way.Each function accepts one dummy argument named obj. Remember that when the function is called, the keyword this is passed to the function. In this case, the this keyword references the <article> tag that caused the event to occur. Thus, each event handler handles the event for two article tags. The first statement gets a list of the child nodes applicable to the current article tag (obj.childNodes). The list is stored in the variable named elements. The for loop works operates as you have seen before. It enumerates all of the elements in the list. However, the list might contains attributes, comments, or text, in addition to a simple list of elements. In other words, getElementsByTagName returns only element types. childNodes returns all elements, text, attributes, and comments. The if statement tests that the type of the current node is an element. We only want to display or hide elements. The inner if statement tests that the tag name is an <h1> tag. This test is performed so that the <h1> tags will never be hidden.Run that pageHANDS-ON EXERCISE: Working with the Google DebuggerIn this exercise, you will again work with the Google JavaScript Debugger. I strongly encourage you to use this debugger and the tools it provides so as help you solve problems as you encounter them.View the page named NavigateArticles.html that you just created. The page must be viewed in Chrome. The Chrome debugging tools are significantly different from the IE debugging tools. Click Shift-Control-J to activate the debugging tools as shown in the following figure:Click the Sources tab to view the document source code.Double click NavigateArticles.htm in the Explorer:Setting Breakpoints:Breakpoints temporarily suspend execution of a program. While suspended, you can look at the value of variables and objects. You set a breakpoint by clicking along the left column of the Sources window (with the line numbers.Click line 11 in the left margin (the executable statement in the inner for loop. A marker appears indicating that the breakpoint is set.Move the mouse over one of the articles causing the event handler to execute. The program is paused at the statement containing the breakpoint. The main window indicates that execution is pausedThe call stack window shows the execution status. The Call stack shows that the function named articleContentShow was called by the onmouseover event. The breakpoint also appears. The right window shows watch expressions. You will create these next. Setting Watchpoints:Watchpoints allow you to view the value of variables and objects as JavaScript executes. You can set multiple watchpoints. When working with objects, the object variable can be expanded to view the values of various properties.Click the Plus sign in the Watch Expressions window. A popup appears allowing you to watch a variable. Enter elements[x] in the editor: You are telling the system to display the xth item in the elements array. The Watch Expressions window should look like the following:Click the arrow to expand the variable.As you can see, the element is a <p> element. Scroll down. Note that Continue to run the program by pressing the play button.HANDS-ON EXERCISE: Working with Input ControlsIn this exercise, you will create a simple input form with widgets, get the input from the widgets, and then perform calculations on that input. You will take two input values, add them together, and display the result.Create a new page named Calculate.html. Create the following widgets on the form in the <body> section.The above code creates two <input> tags allowing the user to enter two numbers. These tags are named inOpOne and inOpTue. The button named btnAdd has an event handler defined named btnAdd_Click(). The <span> tag named lblResult will display the result of adding two numbers together.Create the following onclick event handler for the button. Create this code within a <script> tag within the <head> block of the document. Again, you are creating a procedure that will execute when explicitly called:The above code first declares variables named op1, op2. These two variables are used to get the first two input values stored in the widgets named inOpOne and inOp2.The variable named opResult will store the result of the addition operation. The value property of a text widget contains the value entered by the user. Thus, the statement var op1Value = op1.Value gets the value of the text widget and stores the string in the variable op1Value;The next statements convert the input values into numbers by calling the parseFloat method. Note that these statements store the result in the same variable. Thus, after parseFloat is called, op1Value stores a floating-point value instead of a string. Without converting the data to numbers, the addition operation would concatenate strings, rather than adding two numbers.The final statements add the two operands and store the result into the variable named op3Value. The final statement stores the result into the <span> tag having an id value of lblResult.//12 13 ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download