Sams teach yourself javascript in 24 hours pdf

Tuesday, May 14, 2019 admin Comments(0)

Phil Ballard. Michael Moncur. 24 in. Hours. SamsTeachYourself. JavaScript™. Fifth Edition. Page 3. Sams Teach Yourself JavaScript™ in 24 Hours, Fifth Edition . Copyright © PDF files, JavaScript support in, percent sign (%), Book Description. JavaScript is one of the easiest, most straightforward ways to enhance a website with interactivity. Sams Teach Yourself JavaScript in In just 24 lessons of one hour or less, Sams Teach Yourself JavaScript in 24 Hours helps you learn the fundamentals of programming PDF下载地址( MB).

Language: English, Spanish, Dutch
Country: Lebanon
Genre: Health & Fitness
Pages: 446
Published (Last): 24.11.2015
ISBN: 585-8-24343-425-9
ePub File Size: 30.60 MB
PDF File Size: 10.29 MB
Distribution: Free* [*Regsitration Required]
Downloads: 22743
Uploaded by: VERNITA

Sams Teach Yourself. JavaScript® in 24 Hours. Sixth Edition. Phil Ballard. East 96th Street, Indianapolis, Indiana, USA. in Hours. Michael Moncur. JavaScript. Teach. Yourself. Teach. Yourself Sams Publishing offers excellent discounts on this book when ordered in quantity . JavaScript in 24 Hours, Sams Teach Yourself, lesforgesdessalles.info - Ebook download as PDF File .pdf), Text File .txt) or read book online.

Special Topics. Listing 2. You also dive right in and write some working JavaScript code. The result of running this example is shown in Figure 7. Amazon Related Book Categories: Once written.

Step-by-step instructions carefully walk you through the most common JavaScript programming tasks. See inside for details. Register your book at informit. Those who have at least a basic understanding of HTML and web page design in general and want to move on to adding some extra interactivity to your pages.

Those who currently code in another programming language and want to see what additional capabilities JavaScript can add to your armory. Someone who has never done any computer programming.

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.

JavaScript has a long list of methods for retrieving. Using a date string: The preceding example produces output like the following: Click here to view code image Created: Fri Jan 06 Wed Feb 08 In the preceding code snippet. The preceding example calculates a date 33 days in the future. We can also carry out date and time arithmetic.

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.

In hours 24 sams pdf teach javascript yourself

Caution You always use Math methods directly. Mathematical Constants Various often-used mathematical constants are available as properties of Math. The code would provoke a JavaScript error. Normally we like to specify the possible range of our random numbers. Instead you simply need Math. The keyword with takes an object as an argument.

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.

Remember that JavaScript counts months starting at 0 January and ending in 11 December. At that point the script runs again. Note that the month is displayed as 0. You can retrieve the difference between your local time and UTC time by using the getTimezoneOffset method.

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.

If my loaded page is http: Exercises Modify Listing 4. Use the history object to create a few pages with their own Forward and Back buttons. The volume returned should be rounded up to the nearest cubic meter. In this hour you learn about the JavaScript data types of number. To express numbers falling between the integers. In JavaScript. Numbers Mathematicians have all sorts of names for different types of numbers. The numeric and string data types supported by JavaScript Conversion between data types How to manipulate strings We use the term data type to talk about the nature of the data that a variable contains.

Later you can use it as a string again. From the socalled natural numbers 1. JavaScript supports both integer and floating-point numbers. We also mention escape sequences in strings. Hour 5. A string variable contains a string. If you put a string into your variable and later want to interpret that value as a number. All of the following are valid integers: Hexadecimal numbers begin with 0x.

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.

You can test for non-numerical values with the isNaN function: If the first character in the specified string is a number. The parseFloat function parses a string and returns a floating-point number. Using parseFloat and parseInt JavaScript offers us two functions with which we can force the conversion of a string into a number format.

In most JavaScript implementations. Click here to view code image parseInt You can test for infinite values with the isFinite function. Click here to view code image parseFloat " The isFinite function takes the value to test as an argument and tries to convert that argument into a number. False and true are known as Boolean values. There is also the keyword literal -Infinity to signify the negative infinity. This function allows us to optionally include.

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.

The second parameter number of characters is optional. JavaScript automatically converts true to 1 and false to 0. In the example. It works the other way. JavaScript interprets any nonzero value as true.

JavaScript interprets all of the following values as false: In a practical application. The Negation Operator! JavaScript interprets the! A new dialog will open. Figure 5. Summary In this hour. Normally you assign the value null to something when you want it to have a valid but nonexistent value.

It is a predefined global variable used to store the value of a variable whose name has been used in a statement. For certain implementations. What statement would return a new string created by appending one string called string2 to another string called string1? The JavaScript Specification does not specify a maximum string length. JavaScript also has two keywords called object literals—null and undefined. This means that it is not zero or null.

To do this in JavaScript. Which statement sets the value of variable paid to Boolean true? What is the maximum length of a string in JavaScript? Does JavaScript have a data type to represent a single character?

For a numeric value. Unlike null. Boolean values should not be enclosed in quotes. Write a JavaScript function to capitalize the first letter of each word in a given string. Exercises Write a JavaScript function to remove a given number of characters from the end of a string.

Hour 6. Each value has a numeric index that may contain data of any data type—Booleans. JavaScript has the array data type to help you do this. Arrays An array is a type of object used for storing multiple values in a single variable.

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?

Exercise Review the array and string methods that share a method name. If the element with highest index in array Foo is Foo[8]. JavaScript does not directly support associative arrays arrays with named indexes. Familiarize yourself with how the syntax and operation changes depending on whether these methods are applied to a string or an array. You have an array called monthNames containing the names of all the months of the year.

You can create an array of arrays. How would you use join to create a string name containing all of these month names with a single space between names? You see examples of this later in the book. Does JavaScript allow associative arrays? It will return Can I create a multidimensional array in JavaScript?

To create anything but the simplest scripts. First we declare a variable message. Using conditional statements Comparing values with comparison operators Applying logical operators Writing loops and control structures Setting Timers in JavaScript In Hour 5.

The if Statement In the previous hour we discussed Boolean variables. In this hour we examine ways to recognize particular conditions and have our program act in a prescribed way as a result. JavaScript supports various such conditional statements.

JavaScript has several ways to test such values. The third statement tests the value of the variable bool to see whether it is true. Conditional Statements Conditional statements. We then declare a new variable. It has the following general form: Click here to view code image if this condition is true then do this. Hour 7. Some of the comparison operators are listed in Table 7. Comparison Operators The if statement is not limited to testing the value of a Boolean variable.

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.

JavaScript has an operator. Were we to use this statement. For example: Caution If you need to test whether two items are equal both in value and in type. To achieve this we use the else construct: Click here to view code image condition is true?

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.

Ballard Phil. Sams Teach Yourself JavaScript in 24 Hours

There are many occasions. If the number of repeats is fixed. The only difference is that. All the time the condition keeps coming up true. JavaScript has various built-in loop structures that allow us to achieve such goals.

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.

Now every time while tests the variable count. Looping Through Objects with for. We saw previously that. An infinite loop can stop the browser from responding. The loop will occur once for every property of the supplied object in our example. You can use the for. The result of running this example is shown in Figure 7. To help you. This is especially common when writing user interface routines. JavaScript provides two useful methods.

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.

JavaScript in 24 Hours, Sams Teach Yourself, Sixth Edition

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.

Sams Teach Yourself JavaScript in 24 Hours, 6th Edition

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.

Providing they adhere to these rules. You learn about constructor functions during this hour. For objects. Inheritance—Often when coding you will have a need for some code that is nearly. OOP allows you to reuse your code in a variety of scripts. JavaScript is not one of these.

In the previous hours you often used objects. You could achieve this with regular functions. Writing OOP code offers several advantages over procedural methods: Code reuse—First. Object Creation. You can also easily add a method to the object too. Create a Direct Instance JavaScript has a built-in object simply called Object that you can use as a kind of blank canvas for creating your own objects: You do so because you are trying to assign to method newObject.

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.

Now your object owns a property—in this case a text string containing some information about the object and called info. Caution Notice that you use just the name of the function here without the parentheses. Had you used the code Click here to view code image myNewObject. JavaScript offers several ways to create an object. The window object does not have a property called info. In the context of the showInfo method. You may recall that you used such a keyword in Hour 2. Upon the first declaration of the function myFunc.

Note the use of the this keyword in the previous function definition. When you use this inside a function or method. Loading this page into your browser. Clicking on the first button makes a call to the showInfo method of the newly created object: Instead of this code: JavaScript reports an error. A better way to create objects that will have multiple instances is by using an object constructor function. By using similar assignment statements you can add as many properties and methods as you need to your instantiated object.

Tip An object with only one global instance is sometimes called a singleton object. URL of last page viewed. Take a look at the following code. These objects are useful sometimes. Instead of using new Object. Tip JavaScript offers a further way to create a direct instance of an object. Having defined your constructor function.

You can examine the value stored in the info property for each object by clicking on.

In sams javascript teach pdf hours yourself 24

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.

JavaScript uses the prototype keyword to emulate inheritance, too. Because object. A Pet object has properties that contain the type of animal and the name of the pet, and methods to set these values: Now suppose you want to create an object specifically for dogs.

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.

This variable will hold the reversed string. You then begin a loop, starting at the end of the input string remember that JavaScript string character indexing starts at 0, not 1, so you need to begin at this. As you loop backwards through the string, you add characters one at a time to your output string stored in out. When you reach the beginning of the input string, the reversed string is returned.

The result is shown in Figure 8. How this is achieved varies from language to language, but in JavaScript any variables declared inside the constructor function are available only from within the object; they are invisible from outside. The same is true of any function declared inside the constructor function. Such variables and functions become accessible to the outside world only when they are assigned with the this keyword; they then become properties and methods of the object.

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.

SAMS Teach Yourself Javascript in 24 hours 4th Edition | Technical Books Pdf

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.

Also, when a new browser or version is introduced with new capabilities and features, your browser-detecting code is usually broken once again. Thankfully a much better way to write cross-browser code has emerged, based on objects. JavaScript examine whether the particular feature you need is supported.

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.

If document. Another, related method uses the typeof operator to check whether a JavaScript function exists before calling it: Click here to view code image if typeof document. TABLE 8. Note that at no point in this exercise have you tried to determine what browser your user.

Summary In this hour you learned about object-oriented programming OOP in JavaScript, starting with the basic concepts behind OOP, and how it can help your code development, especially for more complex applications.

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?

Hours yourself javascript in sams teach pdf 24

Some coders prefer to always think in terms of objects, methods, and properties, and write all their code with those principles in mind. Others feel that, particularly for smaller and simpler programs, the level of abstraction provided by OOP is too much, and that procedural coding is OK. How would I use my objects in other programs? If you link into your page a JavaScript file containing an object constructor function, you have the means to create objects and use their properties and methods throughout your 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[0].

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.

Teach in hours 24 javascript pdf sams yourself

You can use this fact to efficiently test whether an element node has a particular attribute defined:. The window that opens is shown in Figure 9. Once installed.. If you use Firefox. You can download it at https: Click here to view code image if myNode. As well as the viewer for the DOM tree. Bear in mind. JavaScript objects. The interface can seem a little daunting at first. Tip When you amend the DOM using the methods described in this hour. Change that. Once created.

If you ask your browser to display the source code of the page. JavaScript has it stored in the newTextNode variable while it waits for you to place it in its required position. At this point it becomes part of the visible page. To do so. You see how to solve these issues shortly. The createTextNode method takes care of that. Passing true to the cloneNode function tells JavaScript that you want to clone not. It works pretty much like createElement.