Skip to main content

NETWORK BASICS

Network A system of interconnected computers and computerized peripherals such as printers is called computer network. This interconnection among computers facilitates information sharing among them. Computers may connect to each other by either wired or wireless media. A computer network consists of a collection of computers, printers and other equipment that is connected together so that they can communicate with each other.  


Network application
A Network application is any application running on one host and provides a communication to another application running on a different host, the application may use an existing application layer protocols such as: HTTP(e.g. the Browser and web server), SMTP(e.g. the email-client). And may be the application does not use any existing protocols and depends on the socket programming to communicate to another application. So the web application is a type of the network applications. 
There are lots of advantages from build up a network, but the th…

Understanding JavaScript and Coding Essentials

Managing and Maintaining JavaScript
Understanding JavaScript and Coding Essentials

HTML5 and CSS3 make a great foundation for your Web site or mobile application. To do anything more than presentation of structured content, though—to respond with individualized data about a specific end user, or transact on-line commerce, or derive results based on data already entered, for instance—takes real programming. JavaScript is a capable programming language with great abilities to express the interactions you want your end users to have with your app.

Think of a service-related mobile application that displays the time of the next service visit to a customer. It offers a hyperlink to telephone a dispatcher in case it’s necessary to reschedule. That’s a silly thing to do, though, outside business hours when no one will be there to answer. How can the hyperlink change, depending on the time of day? Any job of this sort—the kind that, for a human worker, requires a decision, or a calculation, or research—is the province of programming. For us, a computer program is a recipe we direct the computer to execute that results in a particular display or action. Whereas many Web pages are built to be static in that they look the same for all readers, under all circumstances, JavaScript programming makes applications dynamic and interactive; they adjust and respond to particular end users and the actions of those end users. Interactivity enables an end user to take an action in an application, usually by clicking a button or pressing a key. A dynamic application adjusts and responds to such actions by end users. JavaScript also expands the opportunities to animate displays, that is, to have parts of the display move and update while an end user watches. With JavaScript programs, several different elements have to cooperate to get the result you’re after. JavaScript differs from CSS and HTML in a few key aspects, and you’ll learn new concepts to make the best use of JavaScript. HTML and CSS, for example, are largely focused on getting things to look a particular way. In JavaScript, more of the attention is on how things act. To test a JavaScript program, you often need to look at the display at several moments through time, and perhaps to interact with it. Even more than with HTML and CSS, your JavaScript work will depend on a development environment you understand and that makes you comfortable. A useful development environment can be as simple as a copy of Notepad and Internet Explorer, or as complex as an Integrated Development Environment (IDE) with built-in editor, debugger, application generator, and so on. While the exercises in this lesson assume the simplest possible tools, they are easy to adapt to fancier facilities.

The terms program and script are near synonyms. Some people say “script” to emphasize that a source is small, or not in C or Java, or for even more vaguely defined reasons. Don’t worry about the differences. For the purpose of this lesson, the terms program, script, source file, and code are nearly the same.

This lesson focuses on creating JavaScript programs and using functions. You’ll learn how to create simple programs from scratch, and use code from JavaScript libraries, jQuery, and other third-party libraries. You’ll also learn how to locate and access elements, listen and respond to events, show and hide elements, update the content of elements, and add elements on the fly.

CREATE A SIMPLE JAVASCRIPT PROGRAM GET READY. 

To create a simple JavaScript program, perform the following steps: 1. Using an editing or app development tool, create a file with the following content: <!doctype html> <html> <head> <title>My first JavaScript program</title> </head> <body> <h1>My first JavaScript program</h1> <p>This is text. <button type = 'button' on-click = "alert('You clicked the button');">I'm a button; click me</button> </body> </html> 2. Save the file as L8-js1.html.
3. To run the JavaScript program, open L8-js1.html in a Web browser. The results should look similar to Figure 8-1.
If the JavaScript program doesn’t display, you need to enable JavaScript in your Web browser’s preference settings. In Internet Explorer 9, for example, select Tools > Internet options. In the Internet Options dialog box, click the Security tab. Click the Custom level or Default level button, whichever is available. In the Security Settings dialog box, scroll down to the Scripting section (see Figure 8-2). Click the Enable radio button under Active scripting, and then click OK twice to close the dialog boxes. Try opening the L8-js1.html file again in your Web browser to run the JavaScript program.
4. Click the button you created in JavaScript that’s shown on the screen. An alert box displays, as shown in Figure 8-3. This indicates your JavaScript program is working properly.
5. Click OK to close the alert box. 6. Leave the HTML file, editing tool, and Web browser open if you plan to complete the next exercise during this session.
This is your first JavaScript program. Not only does it have a particular appearance on the screen but the appearance changes. This is typical of programs: they respond to user actions. It’s an unusual program, though, in that the JavaScript part of it is nearly invisible. Do you see the JavaScript program? It’s the single fragment within quotes, as follows: alert('You clicked the button'); The alert() itself is too intrusive to appear in production code released for use by consumers, and thus almost never appears in reference documentation. At the same time, it’s the simplest way to start with JavaScript and can be exceedingly useful during development or debugging. An ordinary JavaScript program is a sequence of statements. Statements are separated by semi-colons, as you’ll see in the next exercise.

CREATE A MULTI-STATEMENT JAVASCRIPT PROGRAM GET READY. 

To create a multi-statement JavaScript program, perform the following steps: 1. In an editing or app development tool, update L8-js1.html by replacing the alert() with the following:
alert('This is the first alert'); alert('This is the second alert'); 

2. Save the file.

3. Run the updated JavaScript program by opening the HTML file in a Web browser. 

4. When the first alert box displays, close it by clicking OK. The JavaScript program proceeds to its next statement, that is, the second alert. The second alert is shown in Figure 8-4.

5. Close the second alert box by clicking OK. 

6. Close the HTML file, but leave the editing tool and Web browser open if you plan to complete the next exercise during this session.

Creating and Using Functions

In principle, an entire JavaScript program could be written with one statement following another in the exact sequence they should execute. Programmers have found, however, that it is useful to introduce symbols, or names, for special parts of a program. The first such part is a function. In programming, a function is a segment of a program defined and performed in isolation from other parts. Think for a moment of a cooking recipe. There is no need in each written recipe to explain all the steps involved in extraction of an egg white from an egg; a conventional recipe simply writes, “add one egg white” and assumes that the reader knows to look elsewhere for a detailed “implementation,” or directions on how best to choose an egg, crack open the egg, separate its parts, and so on. 
In the kitchen, it might even be the responsibility of an assistant to prepare egg whites without direct involvement of the person following the recipe. Programming operates analogously; it is common in programming to use functions written by other people, sometimes without close inspection of exactly how they operate. Writing a programming function serves two principal purposes: • A task done in multiple situations can be defined only once and used in multiple cases with confidence its behavior will be the same. This kind of “abbreviation” is more concise and less error-prone than repetition of an entire sequence of steps in each context where the sequence might be needed. • For the convenience of the human who writes, maintains, or reads the program, it is useful and informative to identify meaningful segments of operation with function names. Just as books have chapters, with names that report their actions or themes, computer programs have functions. It’s important to understand that the action of a function is the sequence of the actions of the statements inside of it. When you run a program that contains a function, the program simply runs statements within the function. Also important is to distinguish definition and execution of a function. The expression of a function—the “function example1() {. . .}” part—doesn’t perform any of the code within the function. What you see in the source code is only the definition of a function. Only when the function is invoked or executed or launched—these are synonyms, for our purpose—does something useful happen.
USE A JAVASCRIPT FUNCTION GET READY. To learn how to use a JavaScript function, perform the following steps: 1. In an editing or app development tool, create L8-js2.html with the following content:
<!doctype html> <html> <head> <title>First use of a function</title> <script type = "text/javascript"> function example1() {    alert("This is the first alert.");    alert("This is the second alert."); } </script> </head> <body> <h1>First use of a function</h1> <p>This is text. <button type = 'button' on-click = "example1();">I'm a button; click me</button> </p> </body> </html> 2. Open L8-js2.html in a browser. The program displays, as shown in Figure 8-5. Notice the text and button; at this point, there’s no evidence of JavaScript.
3. Click the button. Compare the action of this page with the behavior of the L8-js1.html file that contains two alerts. Do you see how they act the same although they are written somewhat differently? The alert box looks the same whether called from within a function definition or not. 4. Close the HTML file, but leave the editing tool and Web browser open if you plan to complete the next exercise during this session.
This example introduces at least two other new concepts, beside use of a function. First, it exhibits JavaScript embedded in <script> tags within HTML. There are several ways to “connect” a JavaScript program to the HTML to which it applies. This use of <script> within <head> is common, especially for medium-sized JavaScript projects. Also, the name “example1” of the function deserves attention. This name is under our control. When we write href as part of a hyperlink, or alert() to pop up an alert, we rely on keywords defined in the standards for HTML and JavaScript, respectively. The function name example1, though, is in no such standards. It is our choice. We simply must be consistent; if we write "my_example" instead of “example1” in the definition of the function, then we must also use "my_example". While the function name is under our control, there are a few restrictions on our choice: the name must be made up of letters, digits, underscores, and dollar signs, and the first character of the name must be a letter, underscore, or dollar sign. "example$1" is a possible JavaScript function name, but "not.with.periods", "1wrong", and "first name/last name" are not. JavaScript programs have one other kind of symbolic abbreviation, or name, that’s common. It is a called a variable. While a function names a sequence of actions, a variable stands for a piece of data. You use the var syntax to define a new variable in JavaScript. 

The rules for JavaScript identifiers—basically, the names of variables and functions—are actually somewhat more complicated than written above. Identifiers cannot be the same as words already used in the language; “if”, for example, has a special meaning in JavaScript statements, and is not available as a variable name. However, the characters permitted in a name might be from alphabets other than the English one, under certain circumstances. A full definition of JavaScript’s naming rules is beyond the scope of this lesson.

USE A VARIABLE IN A JAVASCRIPT PROGRAM GET READY

To use a variable in a JavaScript program, perform the following steps: 1. In an editing or app development tool, create L8-js3.html with the following content: <!doctype html> <html> <head> <title>First use of a variable</title> <script type = "text/javascript"> function example1() {    var version_name = "serial number X358-AA-3T601-22"    alert("This is the first alert of " + version_name);    alert("This is the second alert of " + version_name); } </script> </head> <body> <h1>First use of a variable</h1> <p>This is text. <button type = 'button' onclick = "example1();">I'm a button; click me</button> </body> </html> 2. Open L8-js3.html in a browser and click the button. The first alert displays on-screen, as shown in Figure 8-6.

3. Click OK to dismiss the first alert and proceed to the second alert. Do you see how a variable might be useful? A serial number or other important quantity might display in several different places in a program. You don’t have to copy the value in each location; instead, JavaScript lets you use the name of the variable that holds the value.

 4. Click OK to close the second alert box. 5. Close the HTML file, but leave the editing tool and Web browser open if you plan to complete the next exercise during this session.

Using jQuery and Other Third-Party Libraries

The most effective programmers know how to make good use of what others write. A programming library contains snippets of code, subroutines, classes, and other resources you can re-use to create software. There are many JavaScript libraries available, and jQuery is one of the most popular.

Other programmers have already thought about many of the tasks you’ll face, whether your job involves confirmation that credit card numbers are invalid, display of medical images, or construction of a chat facility for a team spread across four continents. You can take advantage of what others have already written by use of JavaScript libraries. A library is collection of resources, like pre-written function code and subroutines, that developers use to create programs. (JavaScript programmers sometimes identify functions that return no value as subroutines.) A JavaScript library is pre-written JavaScript code. 

Most workplaces will already have established before your arrival policy on which libraries to use, and how to invoke them. The Web is full of advice about libraries and their applicability, and supports a rich marketplace of available ones. Many, but not all, are available without fee. Some have more-or-less formal “support” policies, that is, a commitment to respond when faults are reported. Some are intended for only a small number of programmers—a library which facilitates development of applications which control industrial-scale bakeries, for instance—while others are aimed at everyone who codes in JavaScript. jQuery is the leading JavaScript library of this sort. Over half of the 10,000 most-visited Web sites in the world use jQuery. jQuery is available for use with no fee and minimal restriction; you’ll need to consult an attorney, of course, for details on how its licenses apply in your situation. Also note that Microsoft and other industry leaders make copies of jQuery available for anyone to download and use. 

USE JQUERY GET READY. 

To use jQuery, perform the following steps: 1. In an editing or app development tool, create L8-js4.html with the following content: <!doctype html> <html> <head> <title>First use of jQuery</title> <script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.js"></script> <script type = "text/javascript">    // Once the HTML document loads, execute    // the function within ready(). $(document).ready(function() { // Each paragraph receives a "click" action: // hide that particular paragraph.    $("p").click(function() { $(this).hide();    }); });
</script> </head><body> <p>This is the first paragraph. Click on me to make me disappear. <p>This is the second paragraph. <p>This is the third paragraph. </body> </html> 2. Open L8-js4.html in a browser. The page displays, as shown in Figure 8-7. Notice that three sentences display.
3. Click anywhere within the first paragraph. The paragraph disappears, as shown in Figure 8-8.
4. Click anywhere in the second paragraph to make it disappear. 5. Close the HTML file, but leave the editing tool and Web browser open if you plan to complete the next exercise during this session.
Do you see how this is a model for useful behavior in one of your Web or mobile or game console applications? You might want the information displayed to your end users to change depending on circumstances. While it’s possible to write “pure” JavaScript, without jQuery, that behaves as L8-js4.html does, it takes considerably more coding. jQuery makes many common operations shorter, easier to understand, and easier to express correctly. You might be called to use many third-party libraries beside jQuery. Most often, you’ll be given explicit instructions about which library to use. When a choice is available to you, expect to be able to find abundant information on the World Wide Web with a search for the name of the library. Aside from jQuery, other popular libraries include Dojo, MooTools, and YUI. When using a third-party library, you typically need to include an element such as the following: <script type = "text/javascript" src = "web or local address of the JavaScript library source"></script> Why is it necessary to include this tag? When you want to use wonderful_function() from a third-party library in one of the pages you are writing, the only way that the browser knows what you mean by wonderful_function() is through reference to its appearance in the library. The <script ...> provides that reference. You also need to read the documentation for the library you intend to use, and perhaps make licensing arrangements.

Updating the UI by Using JavaScript

You know the basic concepts of HTML: navigation by way of hyperlinks and the Back button, data retrieved on submission of forms, and all the visual styling of traditional HTML markup. Trusty Lawn Care wants an application that does more; it needs to display live updates about crew schedules, respond swiftly and in detail about account information, customize advice depending on the individual and the weather, and much more. Only JavaScript makes all this dynamism and interactivity possible. For an example of what JavaScript makes possible, build a small in-browser calculator.

CREATE AN IN-BROWSER CALCULATOR USING JAVASCRIPT GET READY. 

To create an in-browser calculator using JavaScript, perform the following steps: 1. In an editing or app development tool, create L8-js5.html with the following content: <!doctype html> <html> <head> <title>In-browser calculator</title> </head> </body>
<h1>In-browser calculator</h1> <form name="calculator"> <table border=4> <tr> <td> <input type="text" name="Input" Size="20"> <br> </td> </tr> <tr> <td> <input type="button" name="one"   value="  1  " OnClick="calculator.Input.value
200 | 
+= '1'"> <input type="button" name="two"   value="  2  "   OnCLick="calculator.Input.value += '2'"> <input type="button" name="three" value="  3  "   OnClick="calculator.Input.value += '3'"> <input type="button" name="plus"  value="  +  "   OnClick="calculator.Input.value += ' + '"> <br> <input type="button" name="four"  value="  4  "   OnClick="calculator.Input.value += '4'"> <input type="button" name="five"  value="  5  "    OnCLick="calculator.Input.value += '5'"> <input type="button" name="six"   value="  6  "   OnClick="calculator.Input.value += '6'"> <input type="button" name="minus" value="  -  "   OnClick="calculator.Input.value += ' - '"> <br> <input type="button" name="seven" value="  7  "   OnClick="calculator.Input.value += '7'"> <input type="button" name="eight" value="  8  "   OnCLick="calculator.Input.value += '8'"> <input type="button" name="nine"  value="  9  "   OnClick="calculator.Input.value += '9'"> <input type="button" name="times" value="  x  "   OnClick="calculator.Input.value += ' * '"> <br> <input type="button" name="clear" value="  c  "   OnClick="calculator.Input.value = ''"> <input type="button" name="zero"  value="  0  "    OnClick="calculator.Input.value += '0'"> <input type="button" name="DoIt"  value="  =  "   OnClick="calculator.Input.value = eval(calculator.Input.value)"> <input type="button" name="div"   value="  /  "   OnClick="calculator.Input.value += ' / '"> </td> </tr> </table> </form>
</body> </html>

2. Open L8-js5.html in a browser. The calculator displays as shown in Figure 8-9.

3. Try out your calculator. Click the buttons 7 × 14 + 2 = and observe the result. Did the calculator display 100, as shown in Figure 8-10?

4. Close the HTML file, but leave the editing tool and Web browser open if you plan to complete the next exercise during this session.

This small example illustrates that a JavaScript program can do within the browser essentially anything any other application does, and sometimes in only a few lines of source code. JavaScript capabilities include data entry, response to keyboard strokes and mouse movements, display of results, complex calculations, and more, as the following exercises illustrate. Mobile applications built on an HTML5 basis of course have all the same capabilities.

Locating and Accessing Elements

Often in your programming career, you’ll be able to give an English-language description of what you want—something like, “then we need to check that what the end user has entered is”—but won’t know how to translate the idea into JavaScript. Many times, the challenge will be to identify and isolate what happens with a particular element you see on the screen. “Element” here might be a button, input field, figure, piece of text, or so on. One important way to access display elements is with the getElementById() method. This method returns a reference to the first object with the specified id or NAME attribute. 

“Object” is computer-speak for “thing” or “element”—the most general category of items under consideration. Technically, JavaScript is an “object-based” language, that is, one which emphasizes that such programmatic instances as “first paragraph” have both properties and methods which provide information about the paragraph and opportunities to act on the paragraph.

USE THE GETELEMENTBYID() METHOD FOR USER INPUT GET READY. 

To learn how to use the getElementByID() method to gather user input, perform the following steps: 1. In an editing or app development tool, create L8-js6.html with the following content: <!doctype html> <html> <head> <title>Validation of a user entry</title>
<script type = "text/javascript"> function validate() {    var value = document.getElementById("input1").value;    if (isNaN(value)) { modifier = "not ";    } else { modifier = "";    }    var report = "You entered '" + value + "'; this is " + modifier + "a valid number.";    alert(report); } </script> </head> <body>
<h1>Validation of a user entry</h1> <form name="calculator"> <input type = "text" id = "input1"></input> <button type = "button" onclick = "validate();">Click me to see what I think of your entry</button> </form>
</body> </html> 2. Open L8-js6.html in a browser. 3. Type a short word in the input area and then click the button. The results are shown in Figure 8-11. Click OK to add your changes and close the dialog box.
4. Type a number in the input area and click the button. How did the pop-up message change from the previous step? Click OK to add your changes and close the dialog box. 5. Close the HTML file, but leave the editing tool and Web browser open if you plan to complete the next exercise during this session.
Validation is an important responsibility for JavaScript: has the user entered a figure which fits a budget constraint? Is it a legal credit card number? Is an email address permissible and not in conflict with an existing one? The L8-js6.html file is a small model for the general theme of validation. We often need to confirm that a user’s entry is, in fact, numeric, in the sense that 0 and 3.141 are proper numbers, but abc and 3.141. are not. While it would make sense for JavaScript to have an is_a_number() function, for historical reasons it builds in only isNaN. Why do we call getElementById a “method”? Doesn’t JavaScript build in a library of functions to perform useful tasks? Yes and no. Although JavaScript builds in a library of useful functions for many common operations, some JavaScript capabilities are tied strongly to particular objects HTML defines. These capabilities are called methods. They differ from functions only in that they’re always associated and used with a particular object. isNaN() is an example of a JavaScript function, which tests for “not a number.” If isNaN() returns a value of 0 (false), the value is a number. document.getElementById() is an example of a JavaScript method; you can effectively only use getElementById with the special document object.
Figure 8-11 A model for validation of user input by JavaScript
An “event” is a crucial concept in interactive programming. Much JavaScript programming has to do with responses when something happens. The Load event is commonly used and triggers when its owner is complete.
Listening and Responding to Events
Many application requirements involve events, which are actions that trigger other actions to occur. Descriptions in terms of “when” or “if” are typically coded in JavaScript in terms of events. This can surprise programmers coming from other languages, where the emphasis is on sequence: 1. Do the fi rst thing. 2. Then do the second thing.
3. Then do the third thing. 4. Complete the sequence. Event-based programming, in contrast, looks more like a dialogue: a user takes some action, then the JavaScript program responds, and so on. All the JavaScript example programs presented to this point have involved events. To assign a value to the onClick event handler for the Click event has this effect: “when the end user clicks on the element in question, then execute the script given by the onClick value.” In this case, the click action is the event, and the script is the response, or callback. JavaScript references tabulate all recognized events. Among those often programmed, beyond clicking on an element, are as follows: • submission of a form • keystrokes • other mouse maneuvers including double-clicks and moving the mouse • selection of an item from a listbox • the time when an image has finished loading The onLoad event handler is more important than many beginners recognize. OnLoad “belongs” to HTML items; it triggers when its owner is complete. The onLoad for an <img> image occurs when the image is fully rendered and visible; the onLoad for a <table> fires once all the cells in that table have been drawn. 

USE THE ON-LOAD EVENT HANDLER GET READY. 

To use the onLoad event handler, perform the following steps: 1. In a text editor or app development tool, create L8-js7.html with the following content: <!doctype html> <html> <head> <title>The onLoad event handler</title>
<script type = "text/javascript"> function validate() {    var value = document.getElementById("input1").value;    if (isNaN(value)) { modifier = "not ";    } else { modifier = "";    }    var report = "You entered '" + value + "'; this is " + modifier + "a valid number.";    alert(report); }
function init() {    alert("At this point, it is guaranteed that all HTML elements have loaded.") ; } </script> </head> <body onload = "init();">
<h1>The onLoad event handler</h1> <form name="calculator"> <input type = "text" id = "input1"></input> <button type = "button" onclick = "validate();">Click me to see what I think of your entry</button> </form>
</body> </html> 2. Open L8-js7.html in a browser. A form displays, as shown in Figure 8-12. The alert that’s visible signals the <body> has finished loading; that’s the meaning of onload = "init();".
3. Click OK to close the dialog box. 4. Enter a value in the input field and click the button. Observe this program’s judgment of the value, an example of which is shown in Figure 8-13.
5. Experiment with other values. 6. Close the HTML file, but leave the editing tool and Web browser open if you plan to complete the next exercise during this session.
One common symptom of flawed JavaScript programs is that they are erratic—they give different results at different times. In some cases, this is because the program is written in such a way that it depends on the existence of a particular screen element but doesn’t assure that the element exists. Launching the program at different times can result in slightly different loading order, and thus results that look unpredictable. One tactic for such problems is to begin calculations only after onLoad has “fired,” as in L8-js7.html.

Showing and Hiding Elements

A particular display might show different kinds of information depending on the circumstances: an after-hours telephone number outside of the business day, a warning about usage only during a month with excessive traffic, or notices about the activity of other users only when those other users are logged in. One convenient way to organize such variations is to lay out the display with all possible messages, then show only the pertinent ones. HTML elements have a display attribute useful for this approach. The next exercise has you create a small application that shows and hides a paragraph based on the value an end user enters. The program displays a message if the user enters the value 80 or higher.

HIDE PARTS OF THE DISPLAY BASED ON USER ACTION GET READY. 

To create an application that shows and hides a paragraph based on the value an end user enters, perform the following steps: 1. In a text editor or app development tool, create L8-js8.html with the following contents: <!doctype html> <html> <head> <title>Show/hide responsively</title>
<script type = "text/javascript"> function check_range() {    var value = document.getElementById("price1").value;    var paragraph_list = document.getElementsByTagName("p");    var first_paragraph = paragraph_list[0];    if (value >= 80) { display = "block";    } else { display = "none";    }    first_paragraph.style.display = display; } </script> </head> <body>
<h1>Show/hide responsively</h1> <form> Enter a price: <input type = "number" id = "price1" min = "1" max = "100" oninput = "check_range();"  ></input> </form> <p style = "display:none;">Warning: you are within 20% of your limit.</p>
</body> </html> 2. Open L8-js8.html in a browser. The results are shown in Figure 8-14.
3. Using the keyboard, enter each of these “prices” by pressing the Enter key after each one: 1, 50, 79, 80, 90, and 60. A warning displays after you enter 80 and 90, as shown in Figure 8-15.
4. Close the HTML file, but leave the editing tool and Web browser open if you plan to complete the next exercise during this session.
A common mistake beginners make is to forget one of “show” and “hide.” L8-js8.html begins with the warning paragraph hidden, then uses JavaScript to show it under certain circumstances Remember when you test show/hide functionality that your JavaScript hides again, through assignment of the display attribute, once the conditions for “show” have passed. Otherwise, once it is shown it will never turn off again.
Updating the Content of Elements

The last exercise responded to entry of a price by showing or hiding a warning paragraph. JavaScript has the ability to do far more complex calculations than just a show/hide. It can compute a distance, a recommendation, or, as L8-js9.html shows, a total price. JavaScript uses the inner-HTML property to change the current content of HTML elements (referred to as “inner content”) or insert new content.

UPDATE CONTENT VISIBLE ON THE SCREEN GET READY. 

To create an application that updates content visible on the screen, perform the following steps: 1. In an editing or app development tool, create L8-js9.html with the following content: <!doctype html> <html> <head> <title>Compute element</title>
<script type = "text/javascript">  // check_range assigns the display style  // of the first paragraph as a function of  // the displayed price—whether it's 80 and  // above, or 79 and below. function check_range() {    var value = document.getElementById("price1").value;    var paragraph_list = document.getElementsByTagName("p");    var first_paragraph = paragraph_list[0];    if (value >= 80) { display = "block";    } else { display = "none";    }    first_paragraph.style.display = display; }  // compute_total() has the responsibility  // to update the display with the total of  // the price and its tax. function compute_total() {    var value = document.getElementById("price1").value;    if (isNaN(value)) { total = "INDETERMINATE";    } else { // Assume an 8% tax. total = 1.08 * value; total = total.toFixed(2); var total_slot = document.getElementById("total");    total_slot.innerHTML = total; } </script> </head> <body><h1>Compute element</h1> <form> Enter a price: <input type = "number" id = "price1" min = "1" max = "100" oninput = "check_range(); compute_total();"  ></input> The total price, including tax, is <span id = "total">INDETERMINATE</span>. </form> <p style = "display:none;">Warning: you are within 20% of your limit.</p> </body> </html> 2. Open L8-js9.html in a Web browser. 3. Using the keyboard, type the number 1 in the text box. A message displays, shown in Figure 8-16, showing the price plus 8 percent tax on a $1 item. Notice how quickly and smoothly the display updated.4. Press Enter. 5. Type 50 into the text box and notice how the displayed message changes. 6. Repeat steps 3 and 4 using the values 79, 80, 90, and 60 each time. 7. Close the HTML file, but leave the editing tool and Web browser open if you plan to complete the next exercise during this session.

Adding Elements

JavaScript makes even more radical amendments to a display possible. When necessary, it is possible to create new elements and fit them into an existing display. This is accomplished with the create Element command and the appendChild method.

ADD AN ELEMENT TO THE DISPLAY GET READY. 

To create an application that adds elements to the display, perform the following steps: 1. In an editing or app development tool, create L8-js10.html with the following content: <!doctype html> <html> <head> <title>Create a new element</title> <script type = "text/javascript"> function add_paragraph() {    var original = document.getElementById("original");    var new_paragraph = document.createElement("p");    var current_time = new Date()    var this_text = "This new paragraph appeared at " + current_time + "."; // Even after the browser has rendered // all HTML, it's possible to add *new* // HTML elements.  createTextNode()// appendChild()-insertBefore() is one // typical pattern for adding new textual // content.     var new_content = document.createTextNode(this_text);    new_paragraph.appendChild(new_content);    document.body.insertBefore(new_paragraph, original); } </script> </head> <body> <h1>Create a new element</h1> <p id = "original">This is the text that appears when the display first loads.</p> <button type = "button" onclick = "add_paragraph();">Click on me to     add new content</button> <p style = "display:none;">Warning: you are within 20% of your limit.</p> </body> </html> 2. Open L8-js10.html in a Web browser. The program displays, as shown in Figure 8-17.

Comments

Popular posts from this blog

What if Analysis

What-If Analysis What-If Analysis in Excel allows you to try out different values (scenarios) for formulas. The following example helps you master what-if analysis quickly and easily.  Use scenarios to consider many different variables  A scenario is a set of values that Excel saves and can substitute automatically in cells on a worksheet. You can create and save different groups of values on a worksheet and then switch to any of these new scenarios to view different results. 
Create Different Scenarios 
Note: You can simply type in a different revenue and Cost into cell B2 and B3 respectively to see the corresponding result of a scenario in cell B4. However, what-if analysis enables you to easily compare the results of different scenarios.  
I. On the Data tab, click What-If Analysis and select Scenario Manager from the list. The Scenario Manager Dialog box appears  II. Add a scenario by clicking on Add.  III. Type a name (e.g. “First Case”), select cell B2 and B3 (represents “Revenue” and “…

PROFESSIONAL ENGLISH

Asking For and Giving Opinions on Likes and Dislikes

Words Meaning Sample Sentence Opinion A statement or judgment formed about some matter. Bhoomika gave her final opinion on the company’s matter. Dialogue A conversation between two or more people. Her dialogue stated her opinion about the company’s matter. Expression The action of making known one’s thought or feelings. Her expression was sad at the meeting. Frank An open, honest, and direct speech or writing Bhoomika is very frank with her friends. Recover Return to normal state of health, mind or strength. The company’s economic crisis will be recovered soon. Turmoil A state of great disturbance. The company is facing financial turmoil. Economics The branch of knowledge concerned with the production, consumption, and transfer of wealth. Bhoomika studied Economics at the State University. Betrayed Expose to danger by treacherously giving information to an enemy.

DAILY LIFE VOCABULARY

Apology Etiquette and Office Vocabulary 

Chapter Vocabulary

Word Meaning Sample Sentence Stressed A state of any mental or emotional tension. Ram seems much stressed after his poor exam. Launch An act of instance of starting something. The government launched a new scheme for the poor people. Error A mistake Ravi found a grammatical error in his new grammar book. Scold Blaming someone for any wrong doing Bhuvan scolded his employees for their poor performance. Accuse Claiming that someone has done something wrong. Bharati accuses her friend Chaya for stealing her necklace. Fair Good and honest Ravi got promoted for doing a fair job. Ashamed Embarrassed or guilty because of one’s action. <