|Language:||English, Spanish, Dutch|
|Genre:||Health & Fitness|
|ePub File Size:||30.60 MB|
|PDF File Size:||10.29 MB|
|Distribution:||Free* [*Regsitration Required]|
Browse through an HTML primer before using this book. Stay ahead with the world's most comprehensive technology and business learning platform.
With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more. Start Free Trial No credit card required. View table of contents. Start reading. Practical, hands-on examples show you how to apply what you learn.
Click here to view code image location. TABLE 4. If you would rather the sending page were removed from the history list and replaced with the new URL. This replaces the old URL with the new one both in the browser and in the history list. Use your editor to create the file navigator. Save the file and open it in your browser. Figure 4. Why is it reporting the appName property as Netscape. The result is that the object provides. Not all properties are supported in all browsers hence the failure to report the cpuClass property in the preceding example.
Each Date object we create can represent a different date and time. Querying the navigator object is nearly always the wrong way to do it. Note Later in the book we talk about feature detection.
There is no Date object already created for you as part of the DOM. Create a Date Object with the Current Date and Time This is the simplest way to create a new Date object containing information about the. Although cross-browser standards compliance is closer than it was a few years ago. Dates and Times The Date object is used to work with dates and times. There are several ways to do this: The variable mydate is an object containing information about the date and time at the moment the object was created.
A full list of the methods of the Date object is available in Appendix B. A full list of the available methods is available in Appendix B. Click here to view code image Object created on day number 5 After amending date to 15th. Unlike the Date object. Note the use of toDateString and toTimeString. Finding Minimum and Maximum We can use min and max to pick the largest and smallest number from a list: If the fractional part is less than.
The output as written to the page looks like this: Rounding The methods ceil. As Math. In other words. The youngest person is 19 years old The oldest person is 31 years old Random Numbers To generate a random number. They are listed in Table 4.
The statements within that code block can call methods without specifying an object. Reading the Date and Time We put into practice some of what we covered in this hour by creating a script to get the current date and time when the page is loaded. We also implement a. By using with you can save yourself some tedious typing. Take a look at Listing 4. As we do so. As you will recall. We can access the individual parts of the time and date using getDate.
You worked with browser information from the navigator object.. You learned how to select page elements by their ID using the document. Does Date have methods to deal with time zones? In addition to the get. See Appendix B for a full list of methods. You should use getFullYear and setFullYear instead.
The methods getYear and setYear do exist. Which method of the Math object always rounds a number up to the next integer? What happens when a user clicks OK in a confirm dialog? A value of true is returned when OK is clicked. A value of true is returned to the calling program. Because of the potential problems with dates spanning the millennium. The dialog is cleared and control is returned to the calling program. The location. The displayed message is returned to the calling program.
All the following are valid floating-point numbers: Note In exponential notation. To put it another way.
They can be represented in the traditional way. An integer is a whole number—positive. Not a Number NaN NaN is the value returned when your script tries to treat something non-numerical as a number. Exponential notation provides a compact way to express numbers from the very large to the very small.
If the result is NaN. Click here to view code image isFinite Click here to view code image isNaN 3. You can define an empty string by using two quote marks with nothing between them: Examples include the tab character. To use such a character in a string. Strings A string is a sequence of characters from within a given character set for example. The result of inserting these escape sequences is shown in Figure 5.
You define a string by enclosing it in single or double quotes: Escape Sequences Some characters that you want to put in a string may not have associated keys on the keyboard. Such a combination is known as an escape sequence. This is known as string concatenation. TABLE 5. The first is the starting index—substr extracts the characters from a string. The method returns the index the position of the searched-for substring.
Creating a New Array The syntax used for creating an array will already be familiar to you. What we mean by the array data type How to declare and populate arrays How to manage array contents Sometimes it makes sense to store multiple variable values under a single variable name.
Initializing an Array You can optionally preload data into your array at the time it is created: The following code returns the length of the preceding array: Array Methods Caution Some of the array methods have the same name—and almost the same function— as string methods of the same name.
Be aware of what data type you are working with. TABLE 6. The length property is automatically updated when you add items to or remove items from the array. Suppose we add a new item to the preceding array: Table 6. Click here to view code image myArray. The method returns the index of the searched-for element. Wednesday indexOf We can use indexOf to find the first place where a particular element occurs in an array. The first element sets the location in the array where we want to perform the splice.
Caution Using splice changes the original array! If you need to preserve the array for use elsewhere in your code. In your text editor. Click here to view code image myWeek.
The syntax is a little more complex than that of the previous examples: Click here to view code image array. The method returns any removed elements. We next apply the splice array method to the words array.
Since the splice method. The method returns an array of elements. We store that array in the variable words. In this hour. Since we supply a single space as the argument to join. The wrangleArray function is called by a small script in the body of the document: What value will be returned by indexOf if it is passed a value that does not appear in the array to which it is applied?
Had we assigned a value of false to bool in the second line. TABLE 7. We can test for the Boolean value false by using the negation character! Click here to view code image if! In the case of a Boolean value. Click here to view code image if input.
Now you can further develop that function using the if statement. Now we can see that. Listing 7. Create this file in your editor. Note A more comprehensive list of comparison operators appears in Appendix B.
What if we want to do more than this.. If the value in count is 0 or a number greater than 1. Pass only with great care". If break is omitted. The keyword switch has in parentheses the name of the variable to be tested. The tests themselves are listed within the braces.
This jumps us to the end of the switch statement after having executed the code for a matching case. Each case statement with its value in quotes is followed by a colon. There can be any number of code statements in each section.
Logical Operators There will be occasions when we want to test a combination of criteria to determine whether a test condition has been met.
Depending on the result of the test performed on the data. Note the break statement after each case. The optional default case has its code executed if none of the specified cases were matched.
Each time while evaluates the condition as true.. When count has been decremented to zero. By this time. Click here to view code image var count. The statements in a do. Have a look at the syntax: With the for loop. As in the previous example. Caution Beware accidentally creating an infinite loop. The break command works within a loop pretty much as it does in a switch statement—it kicks us out of the loop and returns operation to the line of code immediately after the closing brace.
You can use it. If later you want to cancel the timer function. You can use the one you feel most comfortable with. Is there a way to stop the current trip around a loop and move straight to the next iteration?
Like setTimeout. Is there any particular reason why I should use one sort of loop over another? Summary In this hour you learned a lot about testing conditions and controlling program flow based on the values of variables.
You also learned a little about using timers in your programs. The setInterval action. It works pretty much like break. Exercises In Hour 4. The break command ends loop execution. How can you modify the code to list the months starting with January as Month 1 rather than Month 0?
There are too many statements in the loop. The condition to terminate the loop is never met. Modify Listing 7. An infinite loop occurs if the condition to terminate the loop is never met. Which of the following is likely to cause an infinite loop to occur? The wrong sort of loop has been used. What command forces the cancellation of a loop. Write a program using a switch statement to output a different message to the user. You might design a general-purpose object called Car.
What object-oriented programming is Two ways to create objects Instantiating an object Extending and inheriting objects using prototype Accessing object methods and properties Using feature detection As your programs become more complex. Procedural programming is characterized by having data stored in variables. For each car in the rental fleet. In object-oriented programming OOP. Hour 8.
What Is Object-Oriented Programming? The code examples to date have been so-called procedural programming. Each instruction or list of instructions. The Car object would have certain properties color. In this hour you learn the basics of object-oriented programming OOP. Using inheritance. We could easily fill the whole book with theory and practice of OOP.
Using the this Keyword. You can begin to rectify that by adding a property: Click here to view code image myNewObject. To call the new method. For the moment.
You can examine the value stored in the info property for each object by clicking on.
The code in Listing 8. The setInfo method takes an argument. Two instances of the object are instantiated. Now you can call its methods and examine its properties: Instantiating an Object You can now create as many instances as you want of this object type.
In doing so. All will have the properties and methods defined in the myObjectType function. Creating an object instance is known as instantiating an object. Note Note that this syntax is identical to using new Object. In the following code.
This overwrites the value stored in the info property of object myNewObject2. As you instantiate two objects. A third button calls the setInfo method of object myNewObject2. The revised values can be checked by once again using Show Info 1 and Show Info 2. Extending Objects What if you want to extend your objects with new methods and properties after the objects have already been instantiated?
You can do so using the keyword prototype. Tip You can define the constructor function to accept as many or as few arguments as you want: Click here to view code image function Car Color. The prototype object allows you to quickly add a property or method that is then available for all instances of the object. Click here to view code image Person.
Extending and Inheriting Objects Using prototype A major advantage of using objects is the capability to reuse already written code in a new context. These techniques are known. Within the constructor. You create two objects. Having created these two person objects. You do so using the prototype keyword. Load the HTML file into your browser. Clicking on the four buttons visible on the page shows that the initially defined showInfo method is still intact, but the new sayHello method operates too, and is available for both of the existing instances of the object type.
Inheritance Inheritance is the capability to create one object type from another; the new object type inherits the properties and methods of the old, as well as optionally having further properties and methods of its own.
Rather than starting from scratch, you want to inherit the Dog object from Pet, but add an additional property, breed, and an additional method, setBreed. Having added the new property, breed, and the new method, setBreed, you can now additionally inherit all the properties and methods of Pet.
You do so using the prototype keyword: You can now access the properties and methods of Pet in addition to those of Dog: You can implement the String. Save the code of Listing 8. The script uses a prompt dialog to invite you to enter a string, and then shows the string reversed on the page. Click here to view code image String. First, you declare a new variable, out, within the anonymous function that you are creating.
In the preceding example, the function volume a,b,c cannot be called from any place outside the constructor function as it has not been assigned to an object method by using this.
However, the property crate. Such methods and properties are referred to as private. It was not uncommon for scripts to be written almost as two or more separate programs, the version to be executed only being decided after an attempt to detect the browser in use. The navigator object contains information that can be misleading at best and sometimes downright incorrect.
You can do this by testing for the availability of a specific object, method, or property. While getElementById has been supported by all new browsers for some time now, very early browsers do not support this method. You can test for the availability of the getElementById method or any similar method or property by using if: Click here to view code image if document.
You learned a way to directly instantiate an object and add properties and methods to it. You then learned to create an object constructor function, from which you can instantiate multiple similar objects. You also learned about the prototype keyword, and how it can be used to extend objects or create new objects via inheritance.
Should I always write object-oriented code?
A new object created from a constructor function is known as: Deriving new objects by using the design of currently existing objects is known as: Encapsulation b. Inheritance c. Instantiation 3. Which of the following is a valid way to create a direct instance of an object? A new object created from a constructor function is known as an instance.
New objects are derived from existing ones through inheritance. Exercises Write a constructor function for a Card object with properties of suit diamonds, hearts, spades, or clubs and face ace, 2, Add methods to set the values of suit and face. Can you include a shuffle method to set the suit and face properties to represent a random card from the deck? Use the Math. Hour 9. By using appropriate methods, you can navigate to any part of the DOM and retrieve details about it.
You probably recall that the top-level object in the DOM hierarchy is the window object, and that one of its children is the document object. In this hour we mainly deal with the document object and its properties and methods. Take a look at the simple web page of Listing 9. Figure 9. Look at how the tree diagram of Figure 9. These two elements are siblings, as they share a parent. Various of these elements of the tree contain text, shown represented in the gray boxes in Figure 9. The DOM is constructed as a hierarchy of such relationships.
The boxes that make up the junctions and terminating points of the tree diagram are known as nodes. Types of Nodes Figure 9. Tip Where they exist, text nodes are always contained within element nodes. However, not every element node contains a text node. Many node types can, of course, contain other nodes as children.
Each different type of node has an associated number known as its nodeType property. The nodeType properties for the various types of nodes are listed in Table 9. TABLE 9. This array-like list is called childNodes, and it enables you to access information about the children of any DOM node.
The childNodes collection is a so-called NodeList, in which the items are numerically indexed. A collection looks and for the most part behaves like an array— you can refer to its members like those of an array, and you can iterate through them like.
For all the examples here, you can treat the collection like you would a regular array. Remember, you can treat the collection pretty much like an array; here you use the length property as you would for an array: Caution Whitespace such as the space and tab characters in HTML code is generally ignored by the browser when rendering the page. This makes simply using childNodes. Using firstChild is equivalent to using childNodes.
To access the last element in the collection, you gain a big advantage by using lastChild. To access this element you would otherwise have to do something like this:. Using parentNode you can go one step back up the tree. When applied to a specified parent node, these read-only properties return the next and previous sibling nodes, respectively, or null if there is no such node.
You generally want to use this to return the text stored in a text node. Node Name The nodeName property returns the name of the specified node as a string value. The values returned by the nodeName value are summarized in Table 9. Another method of the document object, getElementsByTagName , allows you to build an array populated with all of the occurrences of a particular tag. Make careful note of the spelling. Tip Even if there is only one element with the specified tag name, getElementsByTagName still returns a collection, although it will contain only one item.
It can be applied to any individual object and return a collection of elements with the given tag name contained within that object. You can easily implement the same function by using getElementsByTagName. All that remains is to display how many items are in the array: Listing 9. Save this listing as an HTML file and load it into your browser. Check that the result is the same as in Figure 9. A further useful method for getting a collection of elements is Click here to view code image document.
However, this was not supported in Internet Explorer until IE9. The attributes themselves are child nodes of the element node in which they appear, as depicted in Figure 9. If you try to retrieve the value of a nonexistent attribute, getAttribute will return null.