Thứ Tư, 21 tháng 8, 2013

VARIABLES

 Every variable is simply a named placeholder for a value.
var message;
This code defines a variable named messagethat can be used to hold any value.
var message = “hi”;
Here, messageis defined to hold a string value of “hi”. Doing this initialization doesn’t mark
the variable as being a string type; it is simply the assignment of a value to the variable. It is still
possible to not only change the value stored in the variable but also change the type of value, such
as this:
var message = “hi”;
message = 100; //legal, but not recommended
In this example, the variable message is first defined as having the string value “hi”and then
overwritten with the numeric value 100. Though it’s not recommended to switch the data type that
a variable contains, it is completely valid in ECMAScript.
It’s important to note that using the varoperator to define a variable makes it local to the scope in
which it was defined. For example, defining a variable inside of a function using varmeans that the
variable is destroyed as soon as the function exits, as shown here:
function test(){
var message = “hi”; //local variable
}
test();
alert(message); //error!
Here, the message variable is defined within a function using var. The function is called test(),
which creates the variable and assigns its value. Immediately after that, the variable is destroyed so
the last line in this example causes an error. It is, however, possible to define a variable globally by
simply omitting the varoperator as follows:
function test(){
message = “hi”; //global variable
}
test();
alert(message); //”hi”
By removing the var operator from the example, the message variable becomes global. As soon as the function test()is called, the variable is defined and becomes accessible outside of the function once it has been executed.
Although it’s possible to define global variables by omitting the varoperator, this approach is not recommended. Global variables defined locally are hard to maintain and cause confusion, because it’s not immediately apparent if the omission of varwas intentional. Strict mode throws a ReferenceErrorwhen an undeclared variable is assigned a value.If you need to define more than one variable, you can do it using a single statement, separating each variable (and optional initialization) with a comma like this:
var message = “hi”, 
found = false,
age = 29;
Here, three variables are defined and initialized. Because ECMAScript is loosely typed, variable initializations using different data types may be combined into a single statement. Though inserting line breaks and indenting the variables isn’t necessary, it helps to improve readability.When you are running in strict mode, you cannot define variables named evalor arguments. Doing so results in a syntax error.

KEYWORDS AND RESERVED WORDS

break do instanceof typeof
case else new var
catch finally return void
continue for switch while
debugger* function this with
default if throw
delete in try

 The following is the complete list of reserved words
abstract enum int short
boolean export interface static
byte extends long super
char final native synchronized
class float package throws
const goto private transient
debugger implements protected volatile
double import public

The fifth edition shrinks down the list of reserved words when running in nonstrict mode to the following:
class enum extends super
const export import

When running in strict mode, the fifth edition also places reserved word restrictions on the following:
implements package public
interface private static
let protected yield


SYNTAX JAVASCRIPT

Case-sensitivity
The first concept to understand is that everything is case-sensitive; variables, function names, and operators are all case-sensitive, meaning that a variable named testis different froma variable named Test. Similarly, typeof can’t be the name of a function, because it’s a keyword (described in the next section); however, typeOf is a perfectly valid function name.
Identif 
An identifieris the name of a variable, function, property, or function argument. Identifiers may be one or more characters in the following format:The first character must be a letter, an underscore (_), or a dollar sign ($).All other characters may be letters, underscores, dollar signs, or numbers.Letters in an identifier may include extended ASCII or Unicode letter characters such as À and Æ, though this is not recommended.
By convention, ECMAScript identifiers use camel case, meaning that the first letter is lowercase and each additional word is offset by a capital letter, like this:
firstSecond
myCar
doSomethingImportant
Although this is not strictly enforced, it is considered a best practice to adhere to the built-in ECMAScript functions and objects that follow this format
Comments 
ECMAScript uses C-style comments for both single-line and block comments. A single-line comment begins with two forward-slash characters, such as this:
//single line comment
A block comment begins with a forward slash and asterisk (/*) and ends with the opposite (*/), as in this example:
/*
* This is a multi-line
* Comment
*/
Note that even though the second and third lines contain an asterisk, these are not necessary and are added purely for readability. (This is the format preferred in enterprise applications.)
Strict Mode
ECMAScript 5 introduced the concept of strict mode. Strict mode is a different parsing and execution model for JavaScript, where some of the erratic behavior of ECMAScript 3 is addressed and errors are thrown for unsafe activities. To enable strict mode for an entire script, include the following at the top:
“use strict”;
Although this may look like a string that isn’t assigned to a variable, this is a pragma that tells supporting JavaScript engines to change into strict mode. The syntax was chosen specifically so as not to break ECMAScript 3 syntax.You may also specify just a function to execute in strict mode by including the pragma at the top of the function body:
function doSomething(){
“use strict”;
//function body
}
Strict mode changes many parts of how JavaScript is executed, and as such, strict mode distinctions are pointed out throughout the book. Internet Explorer 10+, Firefox 4+, Safari 5.1+, Opera 12+, and Chrome support strict mode.
Statements
Statements in ECMAScript are terminated by a semicolon, though omitting the semicolon makes
the parser determine where the end of a statement occurs, as in the following examples:
var sum = a + b //valid even without a semicolon - not recommended
var diff = a - b; //valid - preferred
Even though a semicolon is not required at the end of statements, it is recommended to always include one. Including semicolons helps prevent errors of omission, such as not finishing what you were typing, and allows developers to compress ECMAScript code by removing extra white space (such compression causes syntax errors when lines do not end in a semicolon). Including semicolons also improves performance in certain situations, because parsers try to correct syntax errors by inserting semicolons where they appear to belong.
Multiple statements can be combined into a code block by using C-style syntax, beginning with a left curly brace ({) and ending with a right curly brace (}):
if (test){
test = false;
alert(test);
}
Control statements, such as if, require code blocks only when executing multiple statements. However, it is considered a best practice to always use code blocks with control statements, even if there’s only one statement to be executed, as in the following examples:
if (test)
alert(test); //valid, but error-prone and should be avoided
if (test){ //preferred
alert(test);
}
Using code blocks for control statements makes the intent clearer, and there’s less chance for errors
when changes need to be made.

Language Basics Javascript


  • Reviewing syntax
  • Working with data types
  • Working with fl ow-control statements
  • Understanding functions
Of particular concern to early browsers was the graceful degradation of pages when the browser didn’t support JavaScript. To that end, the <noscript>element was created to provide alternate content for browsers without JavaScript.
Here is a simple example:
<!DOCTYPE html>
<html>
<head>
<title>Example HTML Page</title>
<script type=”text/javascript” defer=”defer” src=”example1.js”></script>
<script type=”text/javascript” defer=”defer” src=”example2.js”></script>
</head>
<body>
<noscript>
<p>This page requires a JavaScript-enabled browser.</p>
</noscript>
</body>
</html>
In this example, a message is displayed to the user when the scripting is not available. For scriptingenabled browsers, this message will never be seen even though it is still a part of the page.

Document modes

Standards mode is turned on when one of the following doctypes is used:
<!-- HTML 4.01 Strict -->
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
“http://www.w3.org/TR/html4/strict.dtd”>

<!-- XHTML 1.0 Strict -->
<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<!-- HTML5 -->
<!DOCTYPE html>
Almost standards mode is triggered by transitional and frameset doctypes, as follows:
<!-- HTML 4.01 Transitional -->
<!DOCTYPE HTML PUBLIC
“-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>

<!-- HTML 4.01 Frameset -->
<!DOCTYPE HTML PUBLIC
“-//W3C//DTD HTML 4.01 Frameset//EN”
“http://www.w3.org/TR/html4/frameset.dtd”>

<!-- XHTML 1.0 Transitional -->
<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<!-- XHTML 1.0 Frameset -->
<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Frameset//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd”>

Deprecated Syntax

When the <script>element was originally introduced, it marked a departure from traditional HTML parsing. Special rules needed to be applied within this element, and that caused problems for browsers that didn’t support JavaScript (the most notable being Mosaic). Nonsupporting browsers would output the contents of the <script>element onto the page, effectively ruining the page’s appearance.Netscape worked with Mosaic to come up with a solution that would hide embedded JavaScript code from browsers that didn’t support it. The final solution was to enclose the script code in an HTML comment, like this:
<script><!--function sayHi(){
alert(“Hi!”);
}
//--></script>
Using this format, browsers like Mosaic would safely ignore the content inside of the <script>tag, and browsers that supported JavaScript had to look for this pattern to recognize that there was indeed JavaScript content to be parsed.Although this format is still recognized and interpreted correctly by all web browsers, it is no longer necessary and should not be used. In XHTML mode, this also causes the script to be ignored because it is inside a valid XML comment.

Changes javascript in XHTML

Extensible HyperText Markup Language( XHTML) is a reformulation of HTML as an application of XML. The rules for writing code in XHTML are stricter than those for HTML, which affects the <script>element when using embedded JavaScript code. Although valid in HTML, the following code block is invalid in XHTML:
<script type=”text/javascript”>
             function compare(a, b) {
                 if (a < b) {
                     alert(“A is less than B”);
                  } else if (a > b) {
                     alert(“A is greater than B”);
                } else {
                      alert(“A is equal to B”);
              } 
       }
</script>
In HTML, the <script>element has special rules governing how its contents should be parsed; in XHTML, these special rules don’t apply. This means that the less-than symbol (<) in the statement a < b is interpreted as the beginning of a tag, which causes a syntax error because a less-than symbol must not be followed by a space.
There are two options for fixing the XHTML syntax error. The first is to replace all occurrences of he less-than symbol (<) with its HTML entity (&lt;). The resulting code looks like this:

<script type=”text/javascript”>
             function compare(a, b) {
                 if (a &lt;  b) {
                     alert(“A is less than B”);
                  } else if (a > b) {
                     alert(“A is greater than B”);
                } else {
                      alert(“A is equal to B”);
              } 
       }
</script>
This code will now run in an XHTML page; however, the code is slightly less readable. Fortunately, there is another approach.
The second option for turning this code into a valid XHTML version is to wrap the JavaScript code in a CDATA section. In XHTML (and XML), CDATA sections are used to indicate areas of the document that contain free-form text not intended to be parsed. This enables you to use any character, including the less-than symbol, without incurring a syntax error. The format is as follows:
<script type=”text/javascript”><![CDATA[
           function compare(a, b) {
              if (a < b) {
                alert(“A is less than B”);
             } else if (a > b) {
            alert(“A is greater than B”);
            } else {
             alert(“A is equal to B”);
         } 
}
]]></script> 
In XHTML-compliant web browsers, this solves the problem. However, many browsers are still not XHTML-compliant and don’t support the CDATA section. To work around this, the CDATA markup must be offset by JavaScript comments:
<script type=”text/javascript”>
           //<![CDATA[
                 function compare(a, b) {
                    if (a < b) {
                      alert(“A is less than B”);
                  } else if (a > b) {
                     alert(“A is greater than B”);
                   } else {
                    alert(“A is equal to B”);
                  } 
}
               //]]>
</script> 
This format works in all modern browsers. Though a little bit of a hack, it validates as XHTML and degrades gracefully for pre-XHTML browsers.

Asynchronous Scripts

HTML5 introduces the asyncattribute for <script>elements. The asyncattribute is similar to defer
in that it changes the way the script is processed.
For example:
<!DOCTYPE html>
<html>
<head>
<title>Example HTML Page</title>
<script type=”text/javascript” async src=”example1.js”></script>
<script type=”text/javascript” async src=”example2.js”></script>
</head>
<body>
<!-- content here -->
</body>
</html>
In this code, the second script file might execute before the first, so it’s important that there are no
dependencies between the two. The purpose of specifying an asyncscript is to indicate that the
page need not wait for the script to be downloaded and executed before continuing to load, and it
also need not wait for another script to load and execute before it can do the same. Because of this,
it’s recommended that asynchronous scripts not modify the DOM as they are loading.
Asynchronous scripts are guaranteed to execute before the page’s loadevent and may execute
before or after DOMContentLoaded(see Chapter 13 for details). Firefox 3.6, Safari 5, and Chrome 7
support asynchronous scripts.

Deferred Scripts of javascript in HTML

HTML 4.01 defines an attribute named deferfor the <script>element. The purpose of deferis 

to indicate that a script won’t be changing the structure of the page as it executes
Example:
<!DOCTYPE html>
<html>
<head>
<title>Example HTML Page</title>
<script type=”text/javascript” defer src=”example1.js”></script>
<script type=”text/javascript” defer src=”example2.js”></script>
</head>
<body>
<!-- content here -->
</body>

</html>

defer attribute was added beginning with Internet Explorer 4, Firefox 3.5, Safari 5, and Chrome 7. All other browsers simply ignore this attribute and treat the script as it normally would. For this reason, it’s still best to put deferred scripts at the bottom of the page.
For XHTML documents, specify the defer attribute as defer=”defer”

Tag Placement javascript in HTML

All <script>elements were placed within the <head>element on a page, such as in this example:

<!DOCTYPE html>
<html>
<head>
<title>Example HTML Page</title>
<script type=”text/javascript” src=”example1.js”></script>
<script type=”text/javascript” src=”example2.js”></script>
</head>
<body>
<!-- content here -->
</body>
</html>
All JavaScript references in the <body>element, after the page content, as shown in this example:
<!DOCTYPE html>
<html>
<head>
<title>Example HTML Page</title>
</head>
<body>
<!-- content here -->
<script type=”text/javascript” src=”example1.js”></script>
<script type=”text/javascript”  src=”example2.js”></script>
</body>
</html>


JavaScript code inside the script element

Example 1:
<script type=”text/javascript”>
    function sayHi(){
                 alert(“Hi!”);
    }
</script>
Example 2: the following code causes an error when loaded into a browser because </script> not string 
<script type=”text/javascript”>
     function sayScript(){
          alert(“</script>”);
    }
</script>
This problem can be avoided easily by escaping the “/” character, as in this example:
<script type=”text/javascript”>
             function sayScript(){
            alert(“<\/script>”);
             }
</script>
Example 3:The value of srcis a URL linked
<script type=”text/javascript” src=”example.js”></script>

or if javascrip in  XHTML

<script type=”text/javascript” src=”example.js”/>
or
<script type=”text/javascript” src=”http://www.somewhere.com/afile.js”></script>

The script element of javascript in HTML

  • async—Optional. Indicates that the script should begin downloading immediately but should not prevent other actions on the page such as downloading resources or waiting for other scripts to load. Valid only for external script files. charset— Optional. The character set of the code specified using the srcattribute. This attribute is rarely used, because most browsers don’t honor its value.
  • defer— Optional. Indicates that the execution of the script can safely be deferred until after the document’s content has been completely parsed and displayed. Valid only for external scripts. Internet Explorer 7 and earlier also allow for inline scripts.language— Deprecated. Originally indicated the scripting language being used by the code block (such as “JavaScript”, “JavaScript1.2”, or “VBScript”). Most browsers ignore this attribute; it should not be used.
  • src— Optional. Indicates an external file that contains code to be executed.
  • type— Optional. Replaces language; indicates the content type (also called MIME type) of the scripting language being used by the code block. Traditionally, this value has always been “text/javascript”, though both “text/javascript”and “text/ecmascript”are deprecated. JavaScript files are typically served with the “application/x-javascript”MIME type even though setting this in the typeattribute may cause the script to be ignored. Other values that work in non–Internet Explorer browsers are “application/javascript”and “application/ecmascript”. The typeattribute is still typically set to “text/javascript”by convention and for maximum browser compatibility. This attribute is safe to omit, as “text/javascript”is assumed when missing.

Javascript in HTML


  1. Using the <script> element
  2. Comparing inline and external scripts
  3. Examining how document modes affect JavaScript
  4. Preparing for JavaScript-disabled experiences


                                                              Javascript

                                                              JavaScript is a scripting language designed to interact with web pages and is made up of the following three distinct parts:

                                                              • ECMAScript, which is defined in ECMA-262 and provides the core functionality
                                                              • The Document Object Model (DOM), which provides methods and interfaces for working with the content of a web page
                                                              • The Browser Object Model (BOM), which provides methods and interfaces for interacting with the browser
                                                                javascript vn