Sams teach yourself jsp in 24 hours pdf

  1. Maling Ebook
  2. Computer and Internet Books, FREE OnLine Editions: All Books on One Page
  3. java книги, обмен, советы, eBook
  4. Index of /documents/

time you finish Sams Teach Yourself J2EE in 21 Days, you should have the After the servlet or JSP has order of a few minutes—half an hour at most. JavaScript in 24 Hours, Sams Teach Yourself, - Ebook download as PDF File .pdf), Text File .txt) or read book online. vi sams teach yourself java in 24 hours, sixth edition hour sams teach yourself free download here sams teach yourself java jsp in 21 days 3.

Language:English, Spanish, Arabic
Genre:Business & Career
Published (Last):20.01.2016
Distribution:Free* [*Registration Required]
Uploaded by: LIZZETTE

65727 downloads 109739 Views 18.47MB PDF Size Report

Sams Teach Yourself Jsp In 24 Hours Pdf

D:\BIBLIOTECA\Java\Enterprise\[ SUN] Java EE5 D:\ BIBLIOTECA\Java\Enterprise\Teach Yourself J2EE in 21 D:\ BIBLIOTECA\Java\Enterprise\AS\JBoss4\[ Sams] JBoss The Official . Teach Yourself JSP with Apache Tomcat in 24 Indexer Sams teach yourself Ajax, JavaScript, and PHP all in one / Phil Ken He wrote Sams Teach Yourself JavaScript in 24 Hours and has also written are more comfortable with ASP, JSP, or some other server-side Way language. jsp:fallback>, jsp:file>, PDF jsp:forward>, jsp:import>, jsp:include>, , jsp:params>, jsp:text>, jsp:useBean>.

Search for ebooks, tutorials, and articles uploaded Followers Copyright of books goes to its respective owners and we provides you with free download links of ebooks available in world wide web. This is for educative purpose and comes under fair use. So if there is any complaint regarding books copyright, Contact book hosting servers for the removal of the book rather than us. Privacy Policy We are using third party advertisements in this site. Most of our advertisers may use technology such as cookies, web beacons, etc for advertising on our site and it will send information such as your IP address, your Internet service provider name , the browser type, etc to these advertisers including some of your personal information. We never sell your personal information to third parties. If you want to disable cookies, do it in browser settings, but it will not provide full functionality of this site. Google, as a third party vendor, uses cookies to serve ads on this site. Google's use of the DART cookie enables it to serve ads to this site based on your visit to this site and other sites on the Internet. You may opt out of the use of the DART cookie by visiting the Google ad and content network privacy policy. download Books.

Data Types in JavaScript. Converting Between Data Types. Using String Objects. Working with Substrings. Using Numeric Arrays. Using String Arrays. You probably can also figure out how to use a few more without any help.

We will now look at some of the details. Using Variables, Strings, and Arrays Choosing Variable Names Variables are named containers that can store data for example, a number, a text string, or an object. As you learned earlier in this book, each variable has a name. There are specific rules you must follow when choosing a variable name: Variable names can include letters of the alphabet, both upper- and lower- case.

Variable names cannot include spaces or any other punctuation characters. The first character of the variable name must be either a letter or an underscore. Variable names are case sensitive—totalnum, Totalnum, and TotalNum are separate variable names.

There is no official limit on the length of variable names, but they must fit within one line. Using these rules, the following are examples of valid variable names: Do yourself a favor: Use longer, friendly names whenever possible.

Using Local and Global Variables Some computer languages require you to declare a variable before you use it. JavaScript includes the var keyword, which can be used to declare a variable. You can omit var in many cases; the variable is still declared the first time you assign a value to it.

Maling Ebook

To understand where to declare a variable, you will need to understand the concept of scope. There are two types of variables: Global variables have the entire script and other scripts in the same HTML doc- ument as their scope.

They can be used anywhere, even within functions. Using Variables Local variables have a single function as their scope. They can be used only within the function they are created in.

To create a global variable, you declare it in the main script, outside any functions.

You can use the var keyword to declare the variable, as in this example: If this statement is used outside functions, it creates a global variable. The var key- word is optional in this case, so this statement is equivalent to the previous one: Way A local variable belongs to a particular function. Any variable you declare with the var keyword in a function is a local variable. To create a local variable within a function, you must use the var keyword.

This forces JavaScript to create a local variable, even if there is a global variable with the same name. You should now understand the difference between local and global variables. Assigning Values to Variables You can use the equal sign to assign a value to a variable.

For example, this state- ment assigns the value 40 to the variable lines: You have used this syntax earlier to add one to a variable: Using Variables, Strings, and Arrays Because incrementing or decrementing variables is quite common, JavaScript includes two types of shorthand for this syntax. This statement adds one to the value of lines: However, these are not identical. The difference is when the increment or decrement happens: If the operator is after the variable name, the increment or decrement hap- pens after the current expression is evaluated.

If the operator is before the variable name, the increment or decrement hap- pens before the current expression is evaluated. This difference is only an issue when you use the variable in an expression and increment or decrement it in the same statement. As an example, suppose you have assigned the lines variable the value The following two statements have differ- ent effects: The second statement first increments lines to 41, then displays an alert with the value By the These operators are strictly for your convenience.

Understanding Expressions and Operators 85 Understanding Expressions and Operators An expression is a combination of variables and values that the JavaScript inter- preter can evaluate to a single value. Along with variables and constant values, you can also use calls to functions that Did you return results within an expression. Table 6. TABLE 6. For example, consider this statement: Using Variables, Strings, and Arrays If you try to calculate this result, there are two ways to do it.

JavaScript solves this dilemma by following the precedence rules: However, because JavaScript gives division a higher precedence than addition, it will divide the d variable by 4 before adding the other numbers, producing an incorrect result.

You can control precedence by using parentheses. Data Types in JavaScript In some computer languages, you have to specify the type of data a variable will store: However, you should know the types of data JavaScript can deal with. Numbers, such as 3, 25, or 1.

JavaScript supports both integers and floating-point numbers. Boolean, or logical values. These can have one of two values: These are useful for indicating whether a certain condition is true. These consist of one or more characters of text. The null value, represented by the keyword null.

This is the value of an unde- fined variable. For example, the statement document. For example, suppose you declared a variable by assigning it a value: This is a numeric variable. Now suppose you changed the value of total: Although this feature of JavaScript is convenient and powerful, it can also make it By the easy to make a mistake. Because the doc- ument. This works equally well with floating-point and Boolean values. For example, the following statement will work fine if the value of total is In some situations, you might end up with a string containing a number, and need to convert it to a regular numeric variable.

JavaScript includes two functions for this purpose: Both of these functions will read a number from the beginning of the string and return a numeric version.

The nonnumeric portion of the string is ignored. By the These functions look for a number of the appropriate type at the beginning of the Way string. If a valid number is not found, the function will return the special value NaN, meaning not a number. Strings store a group of text characters, and are named similarly to other variables. As a simple example, this statement assigns the string This is a test to a string vari- able called test: There are two ways to create a new String object.

The following two statements create the same string: This tells the browser to create a new String object containing the text This is a test, and assigns it to the variable test. Although you can create a string using object-oriented syntax, the standard By the JavaScript syntax is simpler, and there is no difference in the strings created by Way these two methods.

Assigning a Value You can assign a value to a string in the same way as any other variable. Both of the examples in the previous section assigned an initial value to the string. You can also assign a value after the string has already been created. For example, the fol- lowing statement replaces the contents of the test variable with a new string: Listing 6. For example, this statement adds a period to the current contents of the string sentence: The browser knows By the whether to use addition or concatenation based on the types of data you use with Way the plus sign.

If you use it between a number and a string, the number is convert- ed to a string and concatenated. You can do this with the length property of String objects, which you can use with any string. For example, test.

Here is an exam- ple of this property: The sec- ond statement displays the length of the string—in this case, 15 characters. Remember that although test refers to a string variable, the value of By the test. For example, the following statement displays the value of the test string variable in lowercase: The toUpperCase and toLowerCase methods do not take any parameters, but you still need to use the parentheses.

JavaScript also enables you to work with substrings, or portions of a string. You can use the substring method to retrieve a portion of a string, or the charAt method to get a single character.

These are explained in the following sections. Using Part of a String The substring method returns a string consisting of a portion of the original string between two index values, which you must specify in parentheses.

For example, the following statement displays the fourth through sixth characters of the text string: There are three things you need to understand about the index parameters: Indexing starts with 0 for the first character of the string, so the fourth charac- ter is actually index 3. The second index is noninclusive. A second index of 6 includes up to index 5 the sixth character. Working with Substrings You can specify the two indexes in either order. The smaller one will be assumed to be the first index.

In the previous example, 6,3 would have pro- duced the same result. Of course, there is rarely a reason to use the reverse order. As another example, suppose you defined a string called alpha to hold the alphabet: This is true whenever the two index values are the same.

Getting a Single Character The charAt method is a simple way to grab a single character from a string. The indexes begin at 0 for the first character. Here are a few examples using the alpha string: Using Variables, Strings, and Arrays Finding a Substring Another use for substrings is to find a string within another string. One way to do this is with the indexOf method. To use this method, add indexOf to the string you want to search, and specify the string to search for in the parentheses.

Way Make sure you type it exactly as shown here when you use it in scripts. The value returned in the loc variable is an index into the string, similar to the first index in the substring method.

The first character of the string is index 0. You can specify an optional second parameter to indicate the index value to begin the search. For example, this statement searches for the word fish in the temp string, starting with the 20th character: After finding the first occurrence, you search starting with that location for the second one, and so on. A second method, lastIndexOf , works the same way, but finds the last occurrence of the string.

It searches the string backwards, starting with the last character. For example, this statement finds the last occurrence of Fred in the names string: In this case, the string will be searched backward starting at that location. Using Numeric Arrays An array is a numbered group of data items that you can treat as a single unit. For example, you might use an array called scores to store several scores for a game. Arrays can contain strings, numbers, objects, or other types of data. Each item in an array is called an element of the array.

Using Numeric Arrays 95 Creating a Numeric Array Unlike most other types of JavaScript variables, you typically need to declare an array before you use it. The following example creates an array with four elements: Indexes begin with 0, so the elements of the array in this example would be numbered 0 to 3. These state- ments assign values to the four elements of the array: This statement creates the same scores array in a single line: The following statement is an alternative way to create the scores array: Understanding Array Length Like strings, arrays have a length property.

This tells you the number of elements in the array. For example, these statements would print the number Using Variables, Strings, and Arrays You can declare an array without a specific length, and change the length later by assigning values to elements or changing the length property. For example, these statements create a new array and assign values to two of its elements: Accessing Array Elements You can read the contents of an array using the same notation you used when assigning values.

For example, the following statements would display the values of the first three elements of the scores array: This is an ideal job for loops, which enable you to perform the same statements several times with different values. JavaScript also allows you to use string arrays, or arrays of strings. This is a powerful feature that enables you to work with a large number of strings at the same time.

Creating a String Array You declare a string array in the same way as a numeric array—in fact, JavaScript does not make a distinction between them: Either of the following statements would create the same string array as the preceding example: You can even use the string methods introduced earlier. For example, the following statement prints the first five characters of the first element of the names array, resulting in Henry: To use this method, specify the string to split and a character to divide the parts: The split method in the second statement splits the name string at each space, resulting in three strings.

These are stored in a string array called parts. After the example statements execute, the elements of parts contain the following: This statement reassembles the parts array into a string: In this case, a space is used, resulting in the final string John Q. If you do not specify a character, commas are used. Using Variables, Strings, and Arrays Sorting a String Array JavaScript also includes a sort method for arrays, which returns an alphabetically sorted version of the array.

For example, the following statements initialize an array of four names and sort it: If an array contains the numbers 4, 10, 30, and , for example, it would sort them as 10, , 30, 4—not even close.

The following code sorts a numeric array correctly: After you specify this function in the sort method, the array is sorted in the correct numeric order: By the JavaScript expects the comparison function to return a negative number if a Way belongs before b, 0 if they are the same, or a positive number if a belongs after b.

This is why a-b is all you need for the function to sort numerically. You will create this file next. This document defines a form named theform, a text field named newname, an addname button, and a textarea named sorted.

When you type a name into the text field and click the button, the onclick event han- dler calls the SortNames function.

This function stores the text field value in a vari- able, thename, and then adds the name to the names array using numnames as the index. It then increments numnames to prepare for the next name. The final section of the script sorts the names and displays them. First, the sort method is used to sort the names array.

Next, the join method is used to combine the names, separating them with line breaks, and display them in the textarea. To test the script, save it as sort. You can then add some names and test the script.

Figure 6. You also explored the data types supported by JavaScript and how to convert between them. Using Functions. Introducing Objects. Using Objects to Simplify Scripting.

This is useful for repeating sections of code, and you can also create functions that accept parameters and return val- ues for later use. Whereas functions enable you to group sections of code, objects enable you to group data—you can use them to combine related data items and functions for working with the data.

Although this is a straightforward approach for short scripts, it can be confusing to read a longer script written in this fashion. To use a function, you must first define it. Here is a simple example of a function defi- nition: This begins with the function keyword.

You use these to enclose all of the statements in the function. The browser uses the braces to determine where the function begins and ends.

Computer and Internet Books, FREE OnLine Editions: All Books on One Page

Between the braces, this particular function contains a single line. This uses the built-in alert function, which displays an alert message. If you define a function such as Greet with a Way capital letter, be sure you use the identical name when you call the function. Now, about those parentheses. The current Greet function always does the same thing: Each time you use it, it displays the same message. To make your function more flexible, you can add parameters, also known as argu- ments.

These are variables that are received by the function each time it is called. For example, you can add a parameter called who that tells the function the name of the person to greet. Here is the modified Greet function: Listing 7. However, if you load Listing 7. Making use of a function is referred to as calling the function.

This value will be assigned to the who variable inside the function. Functions can have more than one parameter. To define a function with multiple By the parameters, list a variable name for each parameter, separated by commas.

To Way call the function, specify values for each parameter separated by commas. The second script includes two function calls to the Greet function, each with a different name. Now that you have a script that actually does something, try loading it into a browser. You should see something like Figure 7. This is because JavaScript processing is halted while alerts are displayed. Returning a Value The function you just created displays a message to the user, but functions can also return a value to the script that called them.

This allows you to use functions to cal- culate values. As an example, you can create a function that averages four numbers. We will use the variable names a, b, c, and d for the four numbers to average. Here is the first line of the function: This is a By the common style, but you can also place the brace on the next line, or on a line by Way itself. Next, the function needs to calculate the average of the four parameters.

You can calculate this by adding them, and then dividing by the number of parameters in this case, 4. Thus, here is the next line of the function: The parentheses are necessary to tell JavaScript to perform the addition before the division.

To send this result back to the script that called the function, you use the return keyword. Here is the last part of the function: This statement averages the numbers 3, 4, 5, and 6 and stores the result in a variable called score: Using Functions and Objects Did you You can also use the function call directly in an expression. For example, you Know? Introducing Objects In the previous chapter, you learned how to use variables to represent different kinds of data in JavaScript. JavaScript also supports objects, a more complex kind of vari- able that can store multiple data items and functions.

Although a variable can have only one value at a time, an object can contain mul- tiple values, as well as functions for working with the values. This allows you to group related data items and the functions that deal with them into a single object. DOM objects—Allow your scripts to interact with web pages. Creating Objects When you created an array in the previous chapter, you used the following JavaScript statement: Object Properties and Values Each object has one or more properties—essentially, variables that will be stored within the object.

For example, in Chapter 5, you learned that the location. The href property is one of the properties of the location object in the DOM. The following example sends the browser to a new URL by changing the location. This is referred to as a child By the object. Way Understanding Methods Along with properties, each object can have one or more methods.

For example, the following JavaScript state- ment reloads the current document, as you learned in Chapter 5: Like normal functions, methods can accept arguments in parentheses, and can return values. For example, suppose you are creat- ing a script to work with a business card database that contains names, addresses, and phone numbers for a variety of people. If you were using regular variables, you would need several separate variables for each person in the database: This would be very confusing.

Arrays would improve things slightly. You could have a names array, an addresses array, and a phone number array. Each person in the database would have an entry in each array. This would be more convenient, but still not perfect.

Using Functions and Objects With objects, you can make the variables that store the database as logical as busi- ness cards. Each person is represented by a Card object, which has properties for name, address, and phone number.

You can even add methods to the object to dis- play or work with the information. Defining an Object The first step in creating an object is to name it and its properties.

Each object will have the following properties: This function is called the constructor for an object.

Here is the constructor function for the Card object: This function accepts sever- al parameters from the statement that calls the function, and then assigns them as properties of an object. Because the function is called Card, the object is the Card object. Notice the this keyword. Use this to refer to the current object—the one that is being created by the function. Defining an Object Method Next, you will create a method to work with the Card object.

Because all Card objects will have the same properties, it might be handy to have a function that prints out the properties in a neat format. Here is a function definition for the PrintCard function: The last thing you need to do is make PrintCard part of the function definition for Card objects.

Here is the modified function definition: This will work so long as the PrintCard function is defined with its own function definition.

Methods are essentially properties that define a function rather than a simple value. The previous example uses lowercase names such as workphone for properties, Did you and an uppercase name PrintCard for the method.

You can use any case for Know? To use an object def- inition, you create a new object. This is done with the new keyword. The following statement creates a new Card object called tom: Using Functions and Objects As you can see, creating an object is easy.

All you do is call the Card function the object definition and give it the required attributes, in the same order as the definition. This is called an instance of the Card object. Just as there can be several string variables in a program, there can be several instances of an object you define. Rather than specify all the information for a card with the new keyword, you can assign them after the fact. For example, the following script creates an empty Card object called holmes, and then assigns its properties: For example, this statement displays the properties of the tom card: PrintCard ; Extending Built-in Objects JavaScript includes a feature that enables you to extend the definitions of built-in objects.

This might be very useful if you were creating a large script that used many strings. You can add both properties and methods to an existing object by using the proto- type keyword.

The prototype keyword enables you to change the definition of an object outside its constructor function. You will create a method called heading, which converts a string into an HTML heading.

The follow- ing statement defines a string called title: It accepts a number to specify the heading level. After the function is defined, use the prototype keyword to add it as a method of the String object. You can then use this method on any String object or, in fact, any JavaScript string. This is demonstrated by the last three statements, which dis- play quoted text strings as level 1, 2, and 3 headers.

As a final demonstration of objects, properties, functions, and methods, you will now use this object in a web page to display data for several cards. Your script will need to include the function definition for PrintCard, along with the function definition for the Card object. You will then create three cards and print them out in the body of the document. PrintCard ; phred. PrintCard ; henry. PrintCard ; Notice that the PrintCard function has been modified slightly to make things look good with the captions in boldface.

To use this script, save it as cardtest. However, an object like this could be Way used to store a database record retrieved from a database server with thousands of records. First, you learned how to use functions to group JavaScript statements, and how to call func- tions and use the values they return.

The if Statement. Using Shorthand Conditional Expressions. Testing Multiple Conditions with if and else. Using Multiple Conditions with switch. Using for Loops. Using while Loops. Using do…while Loops. Working with Loops. Looping Through Object Properties Statements in a JavaScript program generally execute in the order in which they appear, one after the other.

Functions, which you learned about in the previous chapter, are one type of flow control— although a function might be defined first thing in your code, its statements can be exe- cuted anywhere in the script. Controlling Flow with Conditions and Loops The if Statement One of the most important features of a computer language is the capability to test and compare values. This allows your scripts to behave differently based on the val- ues of variables, or based on input from the user. The if statement is the main conditional statement in JavaScript.

This statement means much the same in JavaScript as it does in English—for example, here is a typical conditional statement in English: If the phone rings, answer it. This statement consists of two parts: The if statement in JavaScript works much the same way. Here is an example of a basic if statement: This statement checks the variable a and, if it has a value of 1, displays an alert message.

Otherwise, it does nothing.

If you use an if statement like the preceding example, you can use a single state- ment as the action. If it finds a value of 1, it displays a message and sets a back to 0. This is called a conditional expression. A conditional expression usually includes two values to be compared in the preced- ing example, the values were a and 1. These values can be variables, constants, or even expressions in themselves.

The if Statement Either side of the conditional expression can be a variable, a constant, or an By the expression. You can compare a variable and a value, or compare two variables.

Between the two values to be compared is a conditional operator. The Pragmatic Programmer, From Journeyman To Master - Andrew Hunt, David Thomas - Addison Wesley - Straight from the programming trenches, The Pragmatic Programmer cuts through the increasing specialization and technicalities of modern software development to examine the core process--taking a requirement and producing working, maintainable code that delights its users.

It covers topics ranging from personal responsibility and career development to architectural techniques for keeping your code flexible and easy to adapt and reuse. Written as a series of self-contained sections and filled with entertaining anecdotes, thoughtful examples, and interesting analogies, The Pragmatic Programmer illustrates the best practices and major pitfalls of many different aspects of software development.

Martin Series Legacy code. The phrase strikes disgust in the hearts of programmers. It conjures images of slogging through a murky swamp of tangled undergrowth with leaches beneath and stinging flies above. It conjures odors of murk, slime, stagnancy, and offal. Click the link to view the print-fidelity code image. To return to the previous page viewed, click the Back button on your device or app. All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher.

No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. Cover Designer Mark Shirar Compositor Bronkella Publishing Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized.

Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.

Special Sales For information about downloading this title in bulk quantities, or for special sales opportunities which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus, or branding interests , please contact our corporate sales department at corpsales pearsoned.

For government sales inquiries, please contact governmentsales pearsoned. For questions about sales outside the U. Table of Contents Introduction Part I: Objects HOUR 8: HOUR Exercises HOUR Using Libraries Why Use a Library?

Some Popular Libraries Introducing prototype. The document. JavaScript Quick Reference Index. About the Author Phil Ballard, the author of various Sams Teach Yourself titles, graduated in with an honors degree in electronics from the University of Leeds, England.

Following an early career as a research scientist with a major multinational, he spent a few years in commercial and managerial roles within the high technology sector, later working full time as a software engineering consultant. We Want to Hear from You! As the reader of this book, you are our most important critic and commentator. We welcome your comments.

Please note that we cannot help you with technical problems related to the topic of this book. We will carefully review your comments and share them with the author and editors who worked on the book. Reader Services Visit our website and register this book at www. Many advanced programming disciplines used in other programming languages can readily be applied to JavaScript. In the course of the book. With basic features and rather haphazard browser support. JavaScript is an ideal language to use for your first steps in programming.

JavaScript is finally being treated as a serious programming language. Or maybe you currently code in another programming language. Introduction This introduction walks you through a few basic things before you begin reading.

The code examples should work correctly in virtually any recent web browser. For the most part. Answers to the quiz items are conveniently provided immediately following the quiz. Caution Avoid common pitfalls by using the information in these blocks.

Try it Yourself Each hour contains at least one section that walks you through the process of implementing your own script. In addition to the main text of each lesson. Note These sections provide additional comments that might help you to understand the text and examples. Tip These blocks give additional hints. More sophisticated programming paradigms such as program control loops and timers are also covered.

How the Book Is Organized The book is divided into seven parts. This part of the book is aimed mainly at readers with little or no prior programming knowledge. JavaScript debugging. Part V—Using JavaScript Libraries In this part of the book you learn how to simplify cross-browser development using third-party libraries such as jQuery.

Note Appendix A. To see your program code working. The examples in this book can all be created in a text-editing program. Nearly all hosts do. Simply storing the source code file in a convenient location on your computer and opening it with your chosen browser is generally sufficient. At least one such application ships with just about every operating system. It is recommended that you upgrade your browser to the latest current stable version. Check that your web host allows you to run scripts written in the PHP language if you want to try out the Ajax examples in Part V.

The exceptions to this are the hour on cookies and the examples in the book that demonstrate Ajax. Mozilla Firefox. Hour 1. The markup they contain will always be interpreted and displayed in the same way whenever the page is visited by a user.

You also dive right in and write some working JavaScript code. In this first hour we describe what JavaScript is. JavaScript plays a big part in making it all possible. As you know from using the World Wide Web.

Modern web pages can involve audio. Once written. The many functions such scripts can perform include animating page sections. Versus Client-Side Programming There are two fundamental ways of adding scripts to otherwise static web content: You can have the web server execute a script before delivering your page to the user.

These scripts are generally run at the web server before generating the requested web page and serving it to the user. We look at this in Part V.

In the case of a web page. This book is all about JavaScript. Program and script are. Note The term script has no doubt been borrowed from the world of theater and TV. Such scripts can define what information is sent to the browser for display to the user—for example.

You have probably already guessed that this is referred to as client-side scripting. Note There is. A program written in JavaScript can access the elements of a web page.

Virtually every web browser in common use has support for JavaScript. Microsoft introduced jScript. At the same time.

The two languages share some aspects of syntax.

JavaScript in a Nutshell Note Although the names are similar. At the time of writing. Level 1 of the new standardized DOM was completed in late Microsoft browsers have supported in addition to jScript.

The Browser Wars In the late s. Note JavaScript is not the only client-side scripting language. ECMAScript 6 is nearing its final version. Its website at http: Netscape Navigator 4 and Internet Explorer 4 both claimed to offer major improvements over earlier browser versions in terms of what could be achieved with JavaScript. This ludicrous situation forced developers to essentially write two versions of each of their scripts.

Note The term deprecated is applied to software features or practices to indicate that they are best avoided.. The JavaScript instructions are passed to the browser as plain text and are interpreted sequentially. This has long been deprecated.. JavaScript statements.. Although still supported to provide backward compatibility. JavaScript statements. Note JavaScript is an interpreted language. This offers big advantages in that JavaScript programs are easy to read.. Each time your browser is asked to load and display a page.

Internet Explorer is shipping in version As part of this parsing process. In the early days. Since then. Netscape Navigator has been reborn as Mozilla Firefox currently in version As well as DOM Level 0. JavaScript provided rather primitive access to certain parts of a web page.

We discuss how to include JavaScript in your pages in much more detail in Hour 2. Note In this book. It is this model that the browser then refers to when rendering the visible page. The examples in this hour place their JavaScript code within the body section of the document. JavaScript programs could gain access. You are recommended to upgrade your browser to the latest stable version.

Right at the top of the hierarchical tree is the browser window object. Each object also has a list of properties that describe it.

Google Chrome. This book concentrates on more modern browsers that are compatible with DOM Level 1 or better. The situation has improved markedly for web developers. Apart from a few irritating quirks. All of this information is accessible via JavaScript as a parentchild hierarchy of objects.

The window object has various child objects. Any HTML page loaded into the browser creates a document object containing all of the HTML and other resources that go into making up the displayed page. All of these offer excellent support for the DOM. Apple Safari.

The first child object shown in Figure 1. Note The use of early browsers such as Netscape Navigator any version and Internet Explorer up to version 5. The window and document Objects Each time your browser loads and displays a page. These objects. In the DOM. This object is a parent or ancestor to everything else in the DOM representation of your page.

We look in detail at these objects in Hour 4. We can simply use window.. For example object1.

Object Notation The notation we use to represent objects within the tree uses the dot or period: Tip The window object always contains the current browser window. As a shortcut. We begin with two methods. The window object. Here we are calling the alert method of the window object. If you have several windows open. Tip In practice. To refer to one of these documents. When you call the alert method. So Click here to view code image.

Notice that the line of text inside the parentheses is contained within quotation marks. Tip Until the user clicks OK. The appearance of the dialog changes in detail depending on the particular browser.

This line of code. These can be single or double quotes. Try it Yourself: This method. By the time you come to write more advanced JavaScript programs. A dialog that behaves this way is known as a modal dialog. If your browser does this. If you have more than one browser installed on your computer. You should see a display similar to Figure 1.

Caution The default security settings in some browsers cause them to show a security warning when they are asked to open local content. Caution Some text editor programs might try to add a.

Save it to a convenient place on your computer. Be sure your saved file has the extension. Reading a Property of the document Object.. Notice that document. The result is shown in Figure 1. Without the quote marks. Edit hello.

java книги, обмен, советы, eBook

You had an overview of the sorts of things JavaScript can do to enhance your web pages and improve the experience for your users.

In the lessons that follow. You may recall from earlier in the hour that objects in the DOM tree have properties and methods. JavaScript sends to the alert method the value contained in the document. Most definitely. Neither d. A compiled language b. An interpreted language c. The document object. The document method c.

Quiz 1. Other than in extreme circumstances. Is JavaScript a compiled or an interpreted language? The top level of the DOM hierarchy is occupied by: Both 2. How many different browsers should I test in? The document property b. If you have a particularly large piece of JavaScript code. As many as you practically can. Writing standards-compliant code that avoids browser-specific features will go a long way toward making your code run smoothly in different browsers.

In fact. Be careful—property names are case sensitive. The window object is at the top of the DOM tree. The window object Answers 1. Note the capital M.

The program code is written in plain text. JavaScript is an interpreted language. Try the example code from this hour in as many different browsers as you have access to. See whether you can then modify the code to use document. What differences do you note in how the example pages are displayed? Try rewriting that script to instead output the document. Javascript statements are written here.

Various ways to include JavaScript in your web pages The basic syntax of JavaScript statements How to declare and use variables Using mathematical operators How to comment your code Capturing mouse events You learned in Hour 1. Including JavaScript in Your Web Page In the previous hour I said that JavaScript programs are passed to the browser along with page content—but how do we achieve that? If your JavaScript file is not in the same folder as the calling script In this hour you learn more about how JavaScript can be added to your web page.

Hour 2. Just include the raw JavaScript code. Note It is customary to give files of JavaScript code the file extension.

Index of /documents/

This is particularly important in the context of JavaScript libraries. Performance is slightly improved because your browser caches the included file.

When the JavaScript code is updated. You learn about functions in Hour 3. Listing 2. The code for the HTML page is kept cleaner. JavaScript Statements JavaScript programs are lists of individual instructions that we refer to as statements. To interpret statements correctly.. Unless you have a reason to support very old browsers. After the code has been read and executed. A comment written using this syntax can span multiple lines: To ease the readability of your code.

Click here to view code image this is statement 1. We refer to such lines as comments. To add a multiline comment in this way. A comment that occupies just a single line of code can be written by placing a double forward slash before the content of the line: Comments can act as reminders to you.

Many coders of JavaScript. We can set the value stored in netPrice with a simple statement: In CamelCase. Our variables can be called pretty much anything we want. We call this assigning a value to the variable. Generally the difference is so small as to be barely noticeable.

In this example. Such data can take many different forms—an integer or decimal number. JavaScript allows us to carry out operations using the standard arithmetic operators of addition. Having variable names such as productName and netPrice makes code much easier to read and maintain than if the same variables were called var and myothervar Alternatively we can combine these two statements conveniently and readably into one: We could then.

The generated dialog would evaluate the variable and display it this time. Arithmetic Operations First. To assign a character string as the value of a variable. We can use JavaScript to subtract -. To calculate the remainder from a division. We can use variable names in our operations too: Tip If you need to increment or decrement a variable by a value other than one. For example. We can use this notation for other arithmetic operators.

JavaScript uses precedence rules to determine in what order the calculation should be done. The following two lines of code are equivalent: To calculate the average correctly. So are these two: If you have doubts about the precedence rules.

I would recommend that you always use parentheses liberally. You can find detailed information on JavaScript precedence at http: There is no cost to doing so. JavaScript converts the numeric value to a string and concatenates the two: Figure 2. Convert Celsius to Fahrenheit To convert a temperature in degrees Celsius to one measured in degrees Fahrenheit. You should get the result shown in Figure 2. To achieve this. It serves us well for the examples in Part I of this book.. Capturing Mouse Events One of the fundamental purposes of JavaScript is to help make your web pages more interactive for the user.

We are going to investigate three of these: One way we can implement it is to add one more attribute to the HTML element: All of these occurrences we refer to as events. JavaScript deals with events by using so-called event handlers. Click here to view code image alert 'You clicked the button!

In this case. The value given to the onclick attribute is the JavaScript code we want to run when the HTML element in this case a button is clicked.

When the user clicks on the button. This convention has arisen because. Replacing onmouseover with onmouseout in the code will. The onMouseOut event.

When using this within an event handler added via an attribute of an HTML element. Creating an Image Rollover We can use the onMouseOver and onMouseOut events to change how an image appears while the mouse pointer is above it. The code is shown in Listing 2. You can change the image names tick.

You should see that the image changes as the mouse pointer enters. In this example we used two images.

Save the HTML file and open it in your browser. Summary You covered quite a lot of ground this hour. You studied how to declare variables in JavaScript, assign values to those variables, and manipulate them using arithmetic operators.

Does it matter? Empty spaces, such as the space character, tabs, and blank lines, are completely ignored by JavaScript. You can use such blank space, which programmers usually. What is an onClick event handler? A script that executes in response to the user clicking the mouse c. An HTML element that the user can click 2. None b. Exactly one c. Any number 3. Which of these is NOT a true statement about variables?

Their names are case sensitive. They can contain numeric or non-numeric information. Their names may contain spaces. Answers 1. An onClick event handler is a script that executes when the user clicks the mouse.

Variable names in JavaScript must not contain spaces. Exercises Starting with Listing 2. Instead, add an onClick handler to set the. You can access the image title using this. Can you think of an easy way to test whether your script has correctly set the new image title? Hour 3. How to define functions How to call execute functions How functions receive data Returning values from functions About the scope of variables Commonly, programs carry out the same or similar tasks repeatedly during the course of their execution.

For you to avoid rewriting the same piece of code over and over again, JavaScript has the means to parcel up parts of your code into reusable modules, called functions. Using functions also makes your code easier to debug and maintain. There may be 50 places in your code where such calculations are carried out. However, if all such calculations are wrapped up in a few functions used throughout the application, then you just need to make changes to those functions. Your changes will automatically be applied all through the application.

Functions are one of the basic building blocks of JavaScript and will appear in virtually every script you write. In this hour you see how to create and use functions. General Syntax Creating a function is similar to creating a new JavaScript command that you can use in your script.

Inside the braces go the. JavaScript statements that make up the function. In the case of the preceding example, we simply have one line of code to pop up an alert dialog, but you can add as many lines of code as are necessary to make the function Caution The keyword function must always be used in lowercase, or an error will be generated. Calling Functions Code wrapped up in a function definition will not be executed when the page loads.

Instead, it waits quietly until the function is called. To call a function, you simply use the function name with the parentheses wherever you want to execute the statements contained in the function: For example, you may want to add a call to your new function sayHello to the onClick event of a button: Tip Function names, like variable names, are case-sensitive.

A function called MyFunc is different from another called myFunc. JavaScript objects, such as document. Listing 3. The result of clicking the button is shown in Figure 3. Passing Arguments to Functions It would be rather limiting if your functions could only behave in an identical fashion each and every time they were called, as would be the case in the preceding example.

Fortunately, you can extend the capabilities of functions a great deal by passing data to them. You do this when the function is called, by passing to it one or more arguments: Now we can call our function, replacing the variable x with a number. Calling the function like the following results in a dialog box being displayed that contains the result of the calculation, in this case Of course, you could equally pass a variable name as an argument.

The following code would also generate a dialog containing the number Multiple Arguments Functions are not limited to a single argument.

Related articles:

Copyright © 2019 All rights reserved.