JavaScript/Print version
From Wikibooks, the open-content textbooks collection
Contents
- Welcome
- Basics
The SCRIPT Tag
The script element
All JavaScript, when placed in an HTML document, needs to be within a script element. A script element is used to link to an external JavaScript file, or to contain inline scripting (script snippets in the HTML file). A script element to link to an external JavaScript file looks like:
<script type="text/javascript" src="script.js"></script>
while a script element that contains inline JavaScript looks like:
<script type="text/javascript"> // JavaScript code here </script>
Inline scripting has the advantage that both your HTML and your JavaScript is in one file, which is convenient for quick development and testing. Having your JavaScript in a separate file is recommended for JavaScript functions which can potentially be used in more than one page, and also to separate content from behaviour.
Scripting Language
The script element will work in most browsers, because JavaScript is currently the default scripting language. It is strongly recommended though to specify what type of script you are using in case the default scripting language changes.
The scripting language can be specified individually in the script element itself, and you may also use a meta tag in the head of the document to specify a default scripting language for the entire page.
<meta http-equiv="Content-Script-Type" content="text/javascript" />
While the text/javascript was formally obsoleted in April 2006 by RFC 4329 [1] in favour of application/javascript, it is still preferable to continue using text/javascript due to HTML validators' and Internet Explorer web browsers' inability to understand application/javascript [2]
Inline JavaScript
Using inline JavaScript allows you to easily work with HTML and JavaScript within the same page. This is commonly used for temporarily testing out some ideas, and in situations where the script code is specific to that one page.
<script type="text/javascript"> // JavaScript code here </script>
Inline HTML comment markers
The inline HTML comments are to prevent older browsers that do not understand JavaScript from displaying it in plain text.
<script type="text/javascript"> // <!-- // JavaScript code here // --> </script>
The // is a comment delimiter, which prevents the end comment tag --> from being interpreted as JavaScript.
The usage of comment markers is rarely required nowdays, as the browsers that do not recognise JavaScript are virtually non-existent. These early browsers were Mosaic, Netscape 1 and Internet Explorer 2. From Netscape 2.0 in December 1995 and Internet Explorer 3.0 in August 1996 on, browsers were able to interprete javascript.[3]
Inline XHTML JavaScript
In XHTML, the method is somewhat different:
<script type="text/javascript"> // <![CDATA[ // JavaScript code here // ]]> </script>
Note that both the <![CDATA[ tags are commented out. This prevents the browser from mistakenly interpreting strings with XHTML tags as if they were actual XHTML tags.
Linking to external scripts
JavaScript is commonly stored in a file so that it may be used by many web pages on your site. This makes it much easier for updates to occur and saves space on your server. This method is recommended for separating behavior (JavaScript) from content ((X)HTML) and it prevents the issue of incompatibility with inline comments in XHTML and HTML.
Add src="script.js" to the opening script tag. Replace script.js with the path to the .js file containing the JavaScript.
Because the server provides the content type when the file is requested, specifying the type is optional when linking to external scripts. It's still advised to specify the type as text/javascript, in case the server isn't set up correctly, and to prevent HTML validation complaints.
<script type="text/javascript" src="script.js"> </script>
Location of script elements
The script element may appear almost anywhere within the HTML file.
A standard location is within the head element. Placement within the body however is allowed.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Web page title</title> <script type="text/javascript" src="script.js"></script> </head> <body> <!-- HTML code here --> </body> </html>
There are however some best practices for speeding up your web site [4] from the Yahoo! Developer Network that specify a different placement for scripts, to put scripts at the bottom, just before the </body> tag. This speeds up downloading, and also allows for direct manipulation of the DOM while the page is loading.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Web page title</title> </head> <body> <!-- HTML code here --> <script type="text/javascript" src="script.js"></script> </body> </html>
Reference
- ↑ RFC 4329: Scripting Media Types
- ↑ "application/javascript" and "application/ecmasscript" media types not recognized.
- ↑ w:JavaScript#History and naming
- ↑ Yahoo: best practices for speeding up your web site
Bookmarklets
Bookmarklets are one line scripts stored in the URL field of a bookmark. Bookmarklets have been around for a long time so they will work in older browsers.
JavaScript URI scheme
You should be familiar with URL that start with schemes like http and ftp, e.g. http://en.wikibooks.org/. There is also the javascript scheme, which is used to start every bookmarklet.
javascript:alert("Hello, world!");
Using multiple lines of code
Since you cannot have line breaks in bookmarklets you must use a semicolon at the end of each code statement instead.
javascript:name=prompt("What is your name?");alert("Hello, "+name);
The javascript Protocol in Links
The javascript protocol can be used in links. This may be considered bad practice because it prevents access for or confuses users who have disabled JavaScript. See Standards and Best Practices.
<a href="javascript:document.bgColor='#0000FF'">blue background</a>
Examples
A large quantity of links may be found on bookmarklets.com, which show a variety of features that can be performed within Javascript.
Lexical Structure
Case Sensitivity
JavaScript is case sensitive. This means that Hello(); is not the same as HELLO(); or hello();
Whitespace
Whitespace is extra indents, line breaks, and spaces. Javascript ignores it, and it makes the code easier for people to read.
The following is JavaScript with very little whitespace
function filterEmailKeys(evt){ evt=evt||window.event; var charCode=evt.charCode||evt.keyCode; var char=String.fromCharCode(charCode); if(/[a-zA-Z0-9_\-\.@]/.exec(char)) return true; return false; }
The following is the same JavaScript with a typical amount of whitespace
function filterEmailKeys(evt) { evt = evt || window.event; var charCode = evt.charCode || evt.keyCode; var char = String.fromCharCode(charCode); if (/[a-zA-Z0-9_\-\.@]/.exec(char)) { return true; } return false; }
The following is the same JavaScript with a lot of whitespace
function filterEmailKeys(evt) { evt = evt || window.event; var charCode = evt.charCode || evt.keyCode; var char = String.fromCharCode(charCode); if (/[a-zA-Z0-9_\-\.@]/.exec(char)) { return true; } return false; }
Comments
Comments allow you to leave notes in your code to help other people understand it. They also allow you to comment out code that you want to hide from the parser, but you don't want to delete.
Single-line comments
A double slash, //, turns all of the following text on the same line into a comment, that will not be processed by the JavaScript interpreter.
// Shows a welcome message alert("Hello, World!")
Multi-line comments
Multi-line comments are begun with slash asterisk, /*, and end with the reverse, asterisk slash, */
Here is an example of how to use the different types of commenting techniques.
/* This is a multi-line comment that contains multiple lines of commented text */ var a = 1; /* commented out to perform further testing a = a + 2; a = a / (a - 3); // something is wrong here? */ alert('a: ' + a);
Semicolons
In many computer languages semicolons are required at the end of each code statement. In Javascript the use of semicolons is optional, as a new line indicates the end of the statement. This is automatic semicolon insertion and the rules for it are quite complex [1]. Leaving out semicolons and allowing the parser to automatically insert them can create complex problems.
a = b + c (d + e).print()
The above code is not interpreted as two statements. Because of the parenthesis on the second line, JavaScript interprets the above as if it were
a = b + c(d + e).print();
when instead you required it to be interpreted as
a = b + c; (d + e).print();
Even though semicolons are optional, it's preferable to end statements with a semicolon to prevent any misunderstandings from taking place.
Literals
A literal represents a fixed value, as opposed to being a variable.
There are several type of literals available. The most common that comes to mind is the string literal, but there are also integer and floating-point literals, array and boolean literals, as well as object literals too.
Details of these different types are covered in JavaScript/Variables and Types
Identifiers
An identifier is a name for a piece of data such as a variable, array or function.
Identifier Rules
- Letters, dollar signs, underscores and numbers are allowed in identifiers.
- The first character can NOT be a number.
Examples of legal identifiers:
u$hello_Hellohello90
References
- ↑ Standard ECMA-262 ECMAScript Language Specification, Chapter 7.9 - Automatic Semicolon Insertion
Reserved Words
This page contains a list of reserved words in JavaScript, which cannot be used as names of variables, functions or other objects.
Reserved JavaScript keywords
- break
- case
- catch
- continue
- default
- delete
- do
- else
- false
- finally
- for
- function
- if
- in
- instanceof
- new
- null
- return
- switch
- this
- throw
- true
- try
- typeof
- var
- void
- while
- with
Words reserved for JavaScript in the future
These words are reserved by ECMAScript v3 for future versions of JavaScript:
- abstract
- boolean
- byte
- char
- class
- const
- debugger
- double
- enum
- export
- extends
- final
- float
- goto
- implements
- import
- int
- interface
- long
- native
- package
- private
- protected
- public
- short
- static
- super
- synchronized
- throws
- transient
- volatile
Variables and Types
JavaScript is a loosely typed language. What this means is that you can use the same variable for different types of information, but you may also have to check what type a variable is yourself if the differences matter. Like if you wanted to add two numbers, but one variable turned out to be a string, the result wouldn't necessarily be what you expected.
Variable declaration
Variables are commonly explicitly declared by the var statement, as shown below:
var c;
The above variable is created, but has the default value of undefined. To be of value, the variable needs to be initialized:
var c = 0;
Variables can also be created by assigning directly to them, which creates a global variable:
c = 0;
The above is equivalent of assigning the variable to the window object:
window.c = 0;
but creating such global variables is a practice that is best avoided.
Naming variables
When naming variables there are some rules that must be obeyed:
- Upper case and lower case letters of the alphabet, underscores, and dollar signs can be used
- Numbers are allowed after the first character
- No other characters are allowed
- Variable names are case sensitive: different case implies a different name
- A variable may not be a reserved word
Primitive Types
Primitive types are types provided by the system, in this case by javascript. Primitive type for javascript are booleans, numbers and text. In addition to the primitive types, users may define their own classes.
The primitive types are treated by Javascript as value types and when you pass them around they go as values. Some types, such as string, allow method calls.
Boolean Type
Boolean variables can only have 2 possible values, true or false.
var mayday = false; var birthday = true;
Numeric Types
You can use Integer and Float types on your variables, but they are treated as a numeric type.
var sal = 20; var pal = 12.1;
In ECMA Javascript your number literals can go from 0 to -+1.79769e+308. And because 5e-324 is the smallest infinitesimal you can get, anything smaller is rounded to 0.
String Types
The String and char types are all strings, so you can build any string literal that you wished for.
var myName = "Some Name"; var myChar = 'd';
Complex Types
A complex type is an object, be it either standard or custom made. Its home is the heap and goes everywhere by reference.
Array Type
- Main article: JavaScript/Arrays
In Javascript, all Arrays are untyped, so you can put everything you want in an Array and worry about that later. Arrays are objects, they have methods and properties you can invoke at will. (The ".length" property indicates how many things are currently in the array. If you add more things to the array, the value of the ".length" gets larger). You can build yourself an array by using the statement new followed by Array, as shown below.
var myArray = new Array(0, 2, 4); var myOtherArray = new Array();
Arrays can also be created with the array notation, which uses square brackets:
var myArray = [0, 2, 4]; var myOtherArray = [];
Arrays are accessed using the square brackets:
myArray[2] = "Hello"; var text = myArray[2];
It is possible to have thousands of items in an array.
Object Types
An object within Javascript is created using the new operator:
var myObject = new Object();
JavaScript Objects can be built using inheritance and overriding, and you can use polymorphism. There are no scope modifiers, with all properties and methods having public access. More information on creating objects can be found in Object Oriented Programming.
You can access browser built-in objects and objects provided through browser JavaScript extensions.
Numbers
A number is a type of variable which stores an integer.
Basic Use
To make a new integer/number, a simple initialization suffices:
var foo = 0; // or whatever number you want
After you have made your number, you can then modify it as necessary. Numbers can be modified or assigned using the operators defined within JavaScript.
foo = 1; //foo = 1 foo += 2; //foo = 3 (the two gets added on) foo -= 2; //foo = 1 (the two gets removed)
A number literal (which is not linked to a variable) can be used to manipulate these variables by a specific amount. In particular:
- They appear as a set of digits of varying length.
- Negative literal numbers have a minus sign before the set of digits.
- Floating point literal numbers contain one decimal point, and may optionally use the E notation with the character e.
- An integer literal may be prepended with "0", to indicate that a number is in base-8. (9 is not an octal digit, and if found, causes the integer to be read in the normal base-10.)
- An integer literal may also be found with "0x", to indicate a hexadecimal number.
The Math Object
Unlike strings, arrays and dates the integer does not have any objects. However, the Math object may be used. It is an object often used when dealing with numbers. These methods and properties help in the calculation of more complex calculations. The methods and properties of the Math object are referenced using the "dot" operator:
var varOne = Math.ceil(8.5); var varPi = Math.PI;
Methods
random()
Generates a psuedo-random number.
var myInt = Math.random();
max(int1, int2)
Returns the highest number from the two numbers passed as arguments.
var myInt = Math.max(8, 9); document.write(myInt); //9
min(int1, int2)
Returns the lowest number from the two numbers passed as arguments.
var myInt = Math.min(8, 9); document.write(myInt); //8
floor(float)
Returns the greatest integer less than the number passed as an argument.
var myInt = Math.floor(90.8); document.write(myInt); //90;
ceil(float)
Returns the least integer greater than the number passed as an argument.
var myInt = Math.ceil(90.8); document.write(myInt); //91;
round(float)
Returns the closest integer to the number passed as an argument.
var myInt = Math.round(90.8); document.write(myInt); //91;
Properties
Properties of the Math Object are mostly commonly used constants.
- PI: Returns the value of pi.
- E: Returns the constant e.
- SQRT2: Returns the square root of 2.
- LN10: Returns the natural logarithm of 10.
- LN2: Returns the natural logarithm of 2.
Further reading
Strings
A string is a type of variable which stores a string (chain of characters).
Basic Use
To make a new string, you can make a variable and give it a value of new String().
var foo = new String();
But, most developers skip that part and use a string literal:
var foo = "my string";
After you have made your string, you can edit it as you like:
foo = "bar"; //foo = "bar" foo = "barblah"; //foo = "barblah" foo += "bar"; //foo = "barblahbar"
A string literal is normally delimited by the " or ' character, and can normally contain almost any character. Because of the delimiters, it's not possible to directly place either the single or double quote within the string when it's used to start or end the string. In order to work around that limitation, you can place a backslash before the quote to ensure that it appears within the string:
foo = "The cat says, \"Meow!\""; foo = 'It\'s "cold" today.';
Properties and methods of the String() object
As with all objects, Strings have some methods and properties.
replace(text, newtext)
The replace() function returns a string with content replaced.
var foo = "microsoft rox"; var newString = foo.replace("rox", "sux") alert(foo); //microsoft rox alert(newString); //microsoft sux
As you can see, replace() doesn't actually do anything to the 'foo' object at all.
toUpperCase()
This function returns the current string in upper case.
var foo = "Hello!"; alert(foo.toUpperCase()); // HELLO!
toLowerCase()
This function returns the current string in lower case.
var foo = "Hello!"; alert(foo.toLowerCase()); // hello!
length()
Returns the length as an integer.
var foo = "Hello!"; alert(foo.length); // 6
substring()
- "hello".substring(1) => "ello"
- Parameters: start position
- "hello.substring(1,3) => "el"
- Parameters: start position, end position
Further reading
Dates
A Date is an object that contains a given time to millisecond precision.
Basic use
Unlike strings and numbers, the date must be explicitly created with the new operator.
var d = new Date();
The Date object may also be created using paramters within its Constructor. By default, the Date object will contain the current date and time found on the computer, but can be set to any date or time desired.
var y2k_crash = new Date(1999, 12, 31, 23,59,59,999); // One more millisecond, and the world ends!
The date object normally stores the value within the local time zone. If UTC is needed, there are a set of functions available for that use.
The Date object does not support non-CE epochs, but can still represent almost any available time within it's available range.
Properties and methods of the Date() object
As with all objects, the Date() object has methods and properties to manipulate its represented time.
setFullYear(year), getFullYear()
Stores or retrieves the full 4-digit year within the Date object.
setMonth(month, day)
Sets the month within the Date object, and optionally the day within the month.
Note: The Date object uses 0 as January instead of 1.
getMonth()
Returns the current month.
getDate()
Returns the day of the month.
getDay()
Returns the day of the week within the object. Note: Sunday is 0, with the other days of the week taking the next value.
parse(text)
Reads the string text, and returns the number of milliseconds since January 1, 1970.
Further Reading
Arrays
An array is a type of variable that stores a collection of variables. Arrays in JavaScript are zero-based - they start from zero. (instead of foo[1], foo[2], foo[3], JavaScript uses foo[0], foo[1], foo[2].)
Basic use
|
You can also define and set the values for an array with shorthand notation. var foo = ["foo", "fool", "food"] |
To make a new array, make a variable and give it a value of new Array().
var foo = new Array()
After defining it, you can add elements to the array by using the variable's name, and the name of the array element in square brackets.
foo[0] = "foo" foo[1] = "fool" foo[2] = "food"
You can call an element in an array the same way.
alert(foo[2]) //outputs "food"
Exercise
Make an array with "zzz" as one of the elements, and then make an alert box using that element.
Nested arrays
You can put an array in an array.
The first step is to simply make an array. Then make an element (or more) of it an array.
var foo2 = new Array() foo2[0] = new Array() foo2[1] = new Array()
To call/define elements in a nested array, use two sets of square brackets.
foo2[0][0] = "something goes here" foo2[0][1] = "something else" foo2[1][0] = "another element" foo2[1][1] = "yet another" alert(foo2[0][0]) //outputs "something goes here"
You can use shorthand notation with nested arrays, too.
var foo2 = [ ["something goes here","something else"], ["another element","yet another"] ]
Properties and methods of the Array() object
concat()
The concat() method returns the combination of two or more arrays.
To use it, first you need two or more arrays to combine.
var arr1 = ["a","b","c"] var arr2 = ["d","e","f"]
Then, make a third array and set its value to arr1.concat(arr2).
var arr3 = arr1.concat(arr2) //arr3 now is: ["a","b","c","d","e","f"]
join()
The join() method combines all the elements of an array into a single string, separated by a specified delimiter. If the delimiter is not specified, it is set to a comma.
To use it, first make an array.
var abc = ["a","b","c"]
Then, make a new variable and set it to abc.join().
var a = abc.join() //"a,b,c"
You can also set a delimiter.
var b = abc.join("; ") //"a; b; c"
To convert it back into an array with the String object's split() method.
var a2 = a.split(",") //["a","b","c"] var b2 = b.split("; ") //["a","b","c"]
pop() and shift()
The pop() method removes and returns the last element of an array. The shift() method does the same with the first element. (note: The shift() method also changes all the index numbers of the array. For example, arr[0] is removed, arr[1] becomes arr[0], arr[2] because arr[1], and so on.)
First, make an array.
var arr = ["0","1","2","3"]
Then use pop() or shift().
alert(arr) //outputs "0,1,2,3" alert(arr.pop()) //outputs "3" alert(arr) //outputs "0,1,2" alert(arr.shift()) //outputs "0" alert(arr) //outputs "1,2"
push() and unshift()
The push() and unshift() methods reverse the effect of pop() and shift(). The push() method adds an element to the end of an array and returns its new length. The unshift() method does the same with the beginning of the array (and like shift(), also adjusts the indexes of the elements.)
arr.unshift("0") //"0,1,2" arr.push("3") //"0,1,2,3"
Further reading
Operators
Arithmetic Operators
Javascript has the arithmetic operators +, -, *, /, and %. These operators function as the addition, subtraction, multiplication, division and modulus operators, and operate very similarly to the other languages.
var a = 12 + 5; // 17 var b = 12 - 5; // 7 var c = 12 * 5; // 60 var d = 12 / 5; // 2.4 - division results in floating point numbers. var e = 12 % 5; // 2 - the remainder of 12/5 in integer math is 2.
Some mathematical operations, such as dividing by zero, cause the returned variable to be one of the error values - for example, infinity, or NaN.
The return value of the modulus operator maintains the sign of the first operand.
The + and - operators also have unary versions, where they operate only on one variable. When used in this fashion, + returns the number representation of the object, while - returns it's negative counterpart.
var a = "1"; var b = a; // b = "1" a string var c = +a; // c = 1: a number var d = -a; // c = -1: a number
+ is also used as the string concatenation operator: If any of its arguments is a string or is otherwise not a number, any non-string arguments are converted to strings, and the 2 strings are concatenated. For example, 5 + [1,2,3] evaluates to the string "51,2,3". More usefully, str1 + " " + str2 returns str1 concatenated with str2, with a space between.
All other arithmetic operators will attempt to convert their arguments into numbers before evaluating. Note that unlike C or Java, the numbers and their operation results are not guaranteed to be integers.
Bitwise Operators
There are 7 bitwise operators, &, |, ^, ~, >>, <<, and >>>.
These operators convert their operands to integers (truncating any floating point towards 0), and perform the specified bitwise operation on them. The logical bitwise operators, &, |, and ^, perform the and, or, and xor on each individual bit and provides the return value. The ~ inverts all bits within an integer, and usually appears in combination with the logical bitwise operators.
Two bit shift operators, >>, <<, move the bits in one direction which has a similar effect to multiplying or dividing by a power of two. The final bit-shift operator, >>>, operates the same way, but does not preserve the sign bit when shifting.
These operators are kept for parity with the related programming languages but are unlikely to be used in most JavaScript programs.
Assignment operators
The assignment operator = assigns a value to a variable. Primitive types, such as strings and numbers are assigned directly, however function and object names are just pointers to the respective function or object. In this case, the assignment operator only changes the reference to the object rather than the object itself. For example, after the following code is executed, "0,1,0" will be alerted, even though setA was passed to the alert, and setB was changed. This is because they are two references to the same object.
setA = [ 0, 1, 2 ]; setB = setA; setB[2] = 0; alert(setA);
Similarly, after the next bit of code is executed, x is a pointer to an empty array.
z = [5]; x = z; z.pop();
All the above operators have corresponding assignment operators of the form operator=. For all of them, x operator= y is just a convenient abbreviation for x = x operator y.
+=-=*=/=%=&=|=^=>>=<<=>>>=
For example, a common usage for += is in a for loop
var els = document.getElementsByTagName('h2'); var i; for (i = 0; i < els.length; i += 1) { // do something with els[i] }
Increment operators
There are also the increment and decrement operators, ++ and --. a++ increments a and returns the old value of a. ++a increments a and returns the new value of a. The decrement operator functions similarly, but reduces the variable instead.
As an example, the last three lines all perform the same task:
var a = 1; a = a + 1; a += 1; ++a;
Pre and post-increment operators
Increment operators may be applied before or after a variable. When they are applied before a variable they are pre-increment operators, and when they are applied after a variable they are post-increment operators.
The choice of which to use changes how they affect operations.
// increment occurs before a is assigned to b var a = 1; var b = ++a; // a = 2, b = 2; // increment occurs to c after c is assigned to d var c = 1; var d = c++; // c = 2, d = 1;
Due to the possibly confusing nature of pre and post-increment behaviour, code can be easier to read if the increment operators are avoided.
// increment occurs before a is assigned to b var a = 1; a += 1; var b = a; // a = 2, b = 2; // increment occurs to c after c is assigned to d var c = 1; var d = c; c += 1; // c = 2, d = 1;
Comparison operators
The comparison operators determine if the two operands meet the given condition.
==- returns true if the two operands are equal. This operator may convert the operands to the same type (e.g. change a string to an integer).===- returns true if the two operands are identical. This operator will not convert the operands types, and only returns true if they are the same type and value.!=- returns true if the two operands are not equal. This operator may convert the operands to the same type (e.g. change a string to an integer) and returns false if they represent the same value.!==- returns true if the two operands are not identical. This operator will not convert the operands types, and only returns false if they are the same type and value.>- Returns true if the first operands is greater than the second one.>=- Returns true if the first operands is greater than or equal to the second one.<- Returns true if the first operands is less than the second one.<=- Returns true if the first operands is less than or equal to the second one.
Be careful when using == and != as they convert one of the terms being compared so that it's easier to compare. This can lead to strange and non-intuitive situations, such as:
0 == '' // true 0 == '0' // true false == 'false' // false false == '0' // true false == undefined // false false == null // false null == undefined // true
It is better to use === and !== because then you can be sure that the results that you get are those you expect
0 === '' // false 0 === '0' // false false === 'false' // false false === '0' // false false === undefined // false false === null // false null === undefined // false
Logical operators
&&||!
The logical operators are and, or, and not. The && and || operators accept two operands and provides their associated logical result, while the third accepts one, and returns it's logical negation. && and || are short circuit operators. If the result is guaranteed after evaluation of the first operand, it skips evaluation of the second operand.
Technically, the exact return value of these two operators is also equal to the final operand that it evaluated. Due to this, the && operator is also known as the guard operator, and the || operator is also known as the default operator.
function handleEvent(evt) { evt = evt || window.event; var targ = evt.target || evt.srcElement; if (targ && targ.nodeType === 1 && targ.nodeName === 'A') { // ... } }
The ! operator determines the inverse of the given value, and returns the boolean: true values become false, or false values become true.
Note: Javascript represents false by either a boolean false, the number 0, an empty string, or the built in undefined or null type. Any other value is treated as true.
Other operators
? :
The ? : operator (also called the "ternary" operator) is very useful and cool and can replace verbose and complex if/then/else chains. You can replace
if (p && q){ return a; }else{ if (r != s){ return b; }else{ if (t || !v){ return c; }else{ return d; } } }
with
return (p && q) ? a : (r != s) ? b : (t || !v) ? c : d
However, the previous example is a terrible coding style/practice. It is always a bad idea to include nested ternary structures in your programs; whoever comes by to edit or maintain your code (which could very possibly be you) will have a hard time understanding what you meant.
typeof xreturns a string describing the type of x.o instanceof ctests whether o is an object created by the constructor c.delete xunbinds x.new clcreates a new object of type cl. The cl operand must be a constructor function.
Functions and Objects
Functions
Functions allow you to split your code up into separate parts. This commonly allows a complex task to be broken up into several simple tasks, which then become easier to manage and control. When you put your script into a function it keeps the browser from executing the script when the page loads. It contains a code that will be executed by an event or call to that function. It can be called from anywhere within a page or even in an external page. While they can be defined in both <head> and <body> sections it is commonly used in and highly recommended to be used in the <head> portion in order to have your function load before the rest of the page.
Functions are defined with function name() { code }. To call a function, use name().
Functions without arguments
Let us create a function that will perform for us the one of the most common examples when beginning programming. That of saying "Hello, World!"
function helloWorld() { alert('Hello, World!'); }
The above code is saying:
- create a function called helloWorld
- that doesn't expect any arguments
- and perform the following statement, to alert a message
When we want to invoke this function in our HTML document, we call the function in the following manner:
helloWorld();
Let's put this together on a sample web page.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>Some Page</title> <script type="text/javascript">
function helloWorld() {
alert('Hello World!');
}
</script>
</head>
<body>
<p>A web page.</p>
<script type="text/javascript">
helloWorld();
</script>
</body>
</html>
Example
<html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!") } </script> </head> <body> <form> <input type="Button" value="Click Here!" onclick="displaymessage()"> </form> </body> </html>
Since the line "alert("Hello World!")" was placed in a function it will not display until the button is clicked, in which case the alert will pop up.
Functions with arguments
Let's start with a quick example, then we will break it down.
function stepToFive(number) { if (number > 5) { number -= 1; } if (number < 5) { number += 1; } return number; }
This program takes a number as an argument. If the number is larger than 5, it subtracts one. If it's smaller than five it adds one. Let's get down and dirty and look at this piece by piece.
function stepToFive(number) {
This is similar to what we've seen before. We now have number following the function name. This is where we define our arguments for later use, which is similar to defining variables, except in this case the variables are only valid inside of the function.
if (number > 5) {
If statements. If the condition is true, execute the code inside the curly brackets.
number -= 1;
Assuming that JavaScript is your first language, you might not know what this means. This takes one off from the variable number. You can think of it as a useful shorthand for number = number - 1;.
number += 1;
This is similar to the last one, except that it adds one instead of subtracting it.
return number;
This returns the value of number from the function. This will be covered in more depth later on.
Here is an example of using this in a page.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Some Page</title>
<script type="text/javascript">
function stepToFive(number) {
if (number > 5) {
number -= 1;
}
if (number < 5) {
number += 1;
}
return number;
}
</script>
</head>
<body>
<p>
<script type="text/javascript">
var num = stepToFive(6);
alert(num);
</script>
</p>
</body>
</html>
There are a few more things to cover here.
var num = stepToFive(6);
This is where the return statement in the function comes in handy. num here gets assigned the number 5, since that is what stepToFive will return when it's given an argument of 6.
Objects
The philosophy of object-oriented programming says that program code should be as modular as possible. Once you've written and tested a function, it should be possible to slot it into any program or script needing that kind of functionality and just expect it to work, because it's already been tried and tested on an earlier project.
The benefits of this approach are a shorter development time and easier debugging, because you're re-using program code that has already been proven. This 'black box' approach means that data goes into the Object and other data comes out of the Object, but what goes on inside it isn't something you need to concern yourself with.
An Object is a code structure that has its own private variables, and stores data that is isolated from outside interference. Only the Object itself can alter this data. The user works with the data through a set of public functions (called Methods) for accessing these private variables. It's probably most convenient to consider that an Object has its own set of functions that allows you to work with it in certain ways.
While JavaScript allows creating of objects, you will discover that access protection are not directly available in JavaScript; as such, it is possible to bypass the intent of the object-oriented programming by directly accessing fields or methods. To minimize the impact of these issues, you may want to ensure that methods are properly described and cover known situations of use - and to avoid directly accessing methods or fields that are designed to hold the internal state of the object.
Javascript provides a set of predefined Objects. For example: the document itself is an Object, with internal variables like 'title' and 'URL'.
The Date Object
Let's look at the Date Object. You can create a new object and assign it to a variable name using the new keyword:
var mydate = new Date();
The Date Object has a set of internal variables which hold the time, day, month, and year. It allows you to refer to it like a string, so you could for example pop-up the time that the variable was created. A pair of lines like this:
var myDate = new Date(); alert(myDate);
would display an alert box showing the current time and date, in universal time, like this:
|
Tue Jul 26 13:27:33 UTC+1200 2007 |
Even though it produced a string, the variable myDate is not actually one itself. An operator called typeof returns a string that indicates what type the variable is. These types are:
- boolean
- function
- number
- object
- string
- undefined
So the following code:
var myDate = new Date(); alert(typeof myDate);
would produce:
|
object |
The Date Object stores a lot of information about the date, which are accessed using a certain predefined method. Some examples of these methods are:
- getFullYear()
- getMonth()
- getDate()
- getDay()
- getHours()
- getMinutes()
- getSeconds()
The following code shows the year and what type of object that information is.
var myDate = new Date(); var year = myDate.getFullYear(); alert(year + '\n' + typeof(year));
|
2007 |
Because information such as the year are private to the object, the only way we have to alter that information is to use a method provided by the Object for that purpose.
The above methods to get information from the Date object have matching methods that allow you to set them too.
- setFullYear()
- setMonth()
- setDate()
- setDay()
- setHours()
- setMinutes()
- setSeconds()
The following code will show one year, followed by a different year.
var myDate = new Date(); alert(myDate.getFullYear()); myDate.setFullYear(2008); alert(myDate.getFullYear());
| 2007 |
| 2008 |
Defining New Classes
Example:
var site = {}; site.test = function (string) { alert('Hello World! ' + string); site.string = string; } site.test('Boo!'); alert(site.string);
What this example does is:
- Define site as an empty object
- Add a method called test to the site object
- Call the test method with variable "Boo!"
The result is:
- An alert message with "Hello World! Boo!"
- site.string being defined as string
- An alert message with "Boo!".
In summary
An object is a structure of variables and some functions used to work with those variables. These include private variables, which can (or in JavaScript's case, should) only be referenced or changed using the methods it provides. If a Date object's getFullYear() method returns an incorrect value, you can depend on the fact that somewhere in your script, the setFullYear() method has been used to alter it.
this keyword
The this keyword allows a method to read and write the property variables of that instance of the object.
The following example uses an initial capital letter to help indicate that the object needs to be created with the new keyword.
function PopMachine() { this.quarters = 0; this.dollars = 0; this.totalValue = function () { var sum = this.quarters * 25 + this.dollars * 100; return sum; } this.addQuarters = function (increment) { this.quarters += increment; } this.addDollars = function (increment) { this.dollars += increment; } } function testPopMachine() { var popMachine = new PopMachine(); popMachine.addQuarters(8); popMachine.addDollars(1); popMachine.addQuarters(-1); alert('Total in the cash register is: ' + popMachine.totalValue()); } testPopMachine();
Exceptions
In Javascript, errors are created by the Error object and its subclasses. To catch the error to prevent it from stopping your script, you need to enclose sections of your code with the try...catch block.
Errors have two important fields: Error.name - which is the name of the error, and Error.message - a human readable description of the error.
While you can throw any object you want as an exception, it's strongly recommended to throw an instance of the Error object.
Further reading
- "Javascript in Ten Minutes" quickly describes object-oriented JavaScript.
Event Handling
Event Handlers
An event occurs when something happens in a browser window. The kinds of events that might occur are due to:
- A document loading
- The user clicking a mouse button
- The browser screen changing size
When a function is assigned to an event handler, that function is run when that event occurs.
A handler that is assigned from a script used the syntax '[element].[event] = [function];', where [element] is a page element, [event] is the name of the selected event and [function] is the name of the function that occurs when the event takes place.
For example:
document.onclick = clickHandler;
This handler will cause the function clickHandler() to be executed whenever the user clicks the mouse anywhere on the screen. Note that when an event handler is assigned, the function name does not end with parentheses. We are just pointing the event to the name of the function. The clickHandler function is defined like this:
function clickHandler(evt) { //some code here }
By convention the event is represented by the variable 'evt'. In some browsers the event must be explicitly passed to the function, so as a precaution it's often best to include a conditional to test that the evt variable passed been passed, and if it hasn't then to use an alternative method that works on those other browsers.:
function clickHandler(evt) { evt = evt || window.event; //some code here }
Elements within a document can also be assigned event handlers. For example:
document.getElementsByTagName('a')[0].onclick = linkHandler;
This will cause the linkHandler() function to be executed when the user clicks the first link on the page.
Keep in mind that this style of handler assignment depends on the link's position inside the page. If another link tag is added before this one, it will take over the handler from the original link. A best practice is to maintain the separation of code and page structure by assigning each link an identifier by using the id attribute.
<a id="faqLink" href="faq.html">Faq</a>
A handler assignment can then work regardless of where the element is positioned.
document.getElementById('faqLink').onclick = linkHandler;
Standard event handlers
| Attribute | Trigger |
|---|---|
| onabort | Loading of image was interrupted |
| onblur | Element loses focus |
| onchange | Element gets modified |
| onclick | Element gets clicked |
| ondblclick | Element gets double clicked |
| onerror | An error occurred loading an element |
| onfocus | An element received focus |
| onkeydown | A key was pressed when an element has focus |
| onkeypress | A keystroke was received by the element |
| onkeyup | A key was released when the element has focus |
| onload | An element was loaded |
| onmousedown | The mouse button was pressed on the element |
| onmousemove | The mouse pointer moves while inside the element |
| onmouseout | The mouse pointer was moved outside the element |
| onmouseover | The mouse pointer was moved onto the element |
| onmouseup | The mouse button was released on the element. |
| onreset | The form's reset button was clicked |
| onresize | The containing window or frame was resized |
| onselect | Text within the element was selected |
| onsubmit | A form is being submitted |
| onunload | The content is being unloaded (e.g. window being closed) |
Event Handlers as HTML attributes
In HTML, JavaScript events can be included within any specified attribute - for example, a body tag can have an onload event:
<body onload="alert('Hello world!');">
The content of the HTML event attributes is JavaScript code that is interpreted when the event is triggered, and works very similarly to the blocks of JavaScript. This form of code is used when you want to have the JavaScript attached directly to the tag in question.
This type of technique is called inline JavaScript, and can be seen as being a less desirable technique than other unobtrusive JavaScript techniques that have previously been covered. The use of inline JavaScript can be considered to be similar in nature to that of using inline css, where HTML is styled by putting css in style attributes. This is a practice that is best avoided in favour of more versatile techniques.
Regular Expressions
Regular Expressions
JavaScript implements regular expressions (regex for short) when searching for matches within a string. As with other scripting languages, this allows searching beyond a simple letter-by-letter match, and can even be used to parse strings in a certain format.
Unlike strings, regular expressions are bound by the slash (/) character, and may have some options appended.
Regular expressions most commonly appear in conjunction with the string.match() and string.replace() methods.
Compatibility
JavaScript's set of regular expressions follows the extended set. While copying a Regex pattern from JavaScript to another location may work as expected, some older programs may not function as expected.
- In the search term, \1 is used to back reference a matched group, as in other implementations.
- In the replacement string, $1 is substituted with a matched group in the search, instead of \1.
- Example: "abbc".replace(/(.)\1/g, "$1") => "abc"
- | is magic, \| is literal
- ( is magic, \( is literal
Examples
- Matching
- string = "Hello world!".match(/world/);
- stringArray = "Hello world!".match(/l/g); // Matched strings are returned in a string array
- Replacement
- string = string.replace(/expression without quotation marks/g, "replacement");
- string = string.replace(/escape the slash in this\/way/g, "replacement");
- string = string.replace( ... ).replace ( ... ). replace( ... );
- Test
- if (string.match(/regexp without quotation marks/)) {
Modifiers
| Modifier | Note |
|---|---|
| g | Global. The list of matches is returned in an array. |
| i | Case-insensitive search |
| m |
Multiline. If the operand string has multiple lines, ^ and $ match the beginning and end of each line within the string, instead of matching the beginning and end of the whole string only.
|
Operators
| Operator | Effect |
|---|---|
| \b | Matches boundary of a word. |
| \w | Matches an alphanumeric character, including "_". |
| \W | Negation of \w. |
| \s | Matches a whitespace character (space, tab, newline, formfeed) |
| \S | Negation of \s. |
| \d | Matches a digit. |
| \D | Negation of \d. |
See also
- Regular Expressions - a Wikibook dedicated to regular expressions.
- Perl Regular Expressions Reference - a chapter devoted to regular expressions in a book about the Perl programming language.
External links
- JavaScript RegExp Object Reference at W3schools.com
- JavaScript RexExp Tester
Optimization
JavaScript Optimization
Optimization Techniques
- High Level Optimization
- Algorithmic Optimization (Mathemetical Analysis)
- Simplification
- Low Level Optimization
- Loop Unrolling
- Strength Reduction
- Duff's Device
- Clean Loops
Common Mistakes and Misconceptions
Debugging
JavaScript Debuggers
Firebug
- Firebug is a powerful extension for Firefox that has many development and debugging tools including JavaScript debugger and profiler.
Venkman JavaScript Debugger
- Venkman JavaScript Debugger (for Mozilla based browsers such as Netscape 7.x, Firefox/Phoenix/Firebird and Mozilla Suite 1.x)
- Introduction to Venkman
- Using Breakpoints in Venkman
Internet Explorer debugging
- Microsoft Script Debugger (for Internet Explorer) The script debugger is from the Windows 98 and NT era. It has been succeeded by the Developer Toolbar
- Internet Explorer Developer Toolbar
- Microsofts Visual Web Developer Express is Microsofts free version of the Visual Studio IDE. It comes with a JS debugger. For a quick summary of its capabilities see [1]
- Internet Explorer 8 has a firebug-like web development tool by default (no add-on) which can be accessed by pressing F12. The web development tool also provides the ability to switch between the IE8 and IE7 rendering engines.
JTF: Javascript Unit Testing Farm
- JTF is a collaborative website that enables you to create test cases that will be tested by all browsers. It's the best way to do TDD and to be sure that your code will work well on all browsers.
jsUnit
built-in debugging tools
- In Firefox, open "Tools >> Javascript console". This displays errors and warnings for some common typos.
- In Opera 9.5 and above, open "Tools >> Advanced >> Developer Tools" to open Dragonfly. This has many debugging tools such an error console and DOM veiwer.
- Some people prefer to send debugging messages to a "debugging console" rather than use the alert() function.[2][3][4]
- Internet Explorer 8 comes with a firebug-like web development tool that can be accessed by pressing F12. The web development tool has a debugger, DOM viewer, CSS editor, and provides the ability to switch between the IE8 and IE7 rendering engines.
Common Mistakes
- Carefully read your code for typos.
- Be sure that every "(" is closed by a ")" and every "{" is closed by a "}".
- Trailing commas in Array and Object declarations will throw an error in Microsoft Internet Explorer but not in Gecko-based browsers such as Firefox.
// Object
var obj = {
'foo' : 'bar',
'color' : 'red', //trailing comma
};
// Array
var arr = [
'foo',
'bar', //trailing comma
];
- Remember that JavaScript is case sensitive. Look for case related errors.
- Don't use Reserved Words as variable names, function names or loop labels.
- Escape quotes in strings with a "\" or the JavaScript interpreter will think a new string is being started, i.e:
should bealert('He's eating food');alert('He\'s eating food');oralert("He's eating food");
- When converting strings to numbers using the parseInt function, remember that "08" and "09" (e.g. in datetimes) indicate an octal number, because of the prefix zero. Using parseInt using a radix of 10 prevents wrong conversion.
var n = parseInt('09',10); - Remember that JavaScript is platform independent, but is not browser independent. Because there are no properly enforced standards, there are functions, properties and even objects that may be available in one browser, but not available in another, e.g. Mozilla / Gecko Arrays have an indexOf() function; Microsoft Internet Explorer does not.
Debugging Methods
Debugging in Javascript doesn't differ very much from debugging in most other programming languages. See the article at Computer programming/debugging.
Following Variables as a Script is Running
The most basic way to inspect variables while running is a simple alert() call. However some development environments allow you to step through your code, inspecting variables as you go. These kind of environments may allow you to change variables while the program is paused.
Browser Bugs
Sometimes the browser is buggy, not your script. This means you must find a workaround.
browser-dependent code
Some advanced features of Javascript don't work in some browsers.
Too often our first reaction is: Detect which browser the user is using, then do something the cool way if the user's browser is one of the ones that support it. Otherwise skip it.
Instead of using a "browser detect", a much better approach is to write "object detection" Javascript to detect if the user's browser supports the particular object (method, array or property) we want to use.[5] [6]
To find out if a method, property, or other object exists, and run code if it does, we write code like this:
var el = null; if (document.getElementById) { // modern technique el = document.getElementById(id); } else if (document.all) { // older Internet Explorer technique el = document.all[id]; } else if (document.layers) { // older Netscape web browser technique el = document.layers[id]; }
For further reading
- "Javascript Debugging" by Ben Bucksch
DHTML
DHTML (Dynamic HTML) is a combination of JavaScript, CSS and HTML.
alert messages
<script type="text/javascript"> alert('Hello World!'); </script>
This will give a simple alert message.
<script type="text/javascript"> prompt('What is your name?'); </script>
This will give a simple prompt message.
<script type="text/javascript"> confirm('Are you sure?'); </script>
This will give a simple confirmation message.
Javascript Button and Alert Message Example:
Sometimes it is best to dig straight in with the coding. Here is an example of a small piece of code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>"THE BUTTON" - Javascript</title> <script type="text/javascript"> x = 'You have not pressed "THE BUTTON"' function bomb() { alert('O-GOD NOOOOO, WE ARE ALL DOOMED!!'); alert('10'); alert('9'); alert('8'); alert('7'); alert('6'); alert('5'); alert('4'); alert('3'); alert('2'); alert('1'); alert('!BOOM!'); alert('Have a nice day. :-)'); x = 'You pressed "THE BUTTON" and I told you not to!'; } </script> <style type="text/css"> body { background-color:#00aac5; color:#000 } </style> </head> <body> <div> <input type="button" value="THE BUTTON - Don't Click It" onclick="bomb()"><br /> <input type="button" value="Click Here And See If You Have Clicked ''THE BUTTON''" onclick="alert(x)"> </div> <p> This script is dual-licensed under both, <a href="http://www.wikipedia.org/wiki/GNU_Free_Documentation_License">GFDL</a> and <a href="GNU General Public License">GPL</a>. See <a href="http://textbook.wikipedia.org/wiki/Programming:Javascript">Wikibooks</a> </p> </body> </html>
What has this code done? Well when it loads it tells what value the variable 'x' should have. The next code snippet is a function that has been named "bomb". The body of this function fires some alert messages and changes the value of 'x'.
The next part is mainly HTML with a little javascript attached to the INPUT tags. "onclick" property tells its parent what has to be done when clicked. The bomb function is assigned to the first button, the second button just shows an alert message with the value of x.
Javascript if() - else Example
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>The Welcome Message - Javascript</title> <script type="text/javascript"> function wlcmmsg() { name = prompt('What is your name?', ''); correct = confirm('Are you sure your name is ' + name + ' ?'); if (correct == true) { alert('Welcome ' + name); } else { wlcmmsg(); } } </script> <style type="text/css"> body { background-color:#00aac5; color:#000 } </style> </head> <body onload="wlcmmsg()" onunload="alert('Goodbye ' + name)"> <p> This script is dual-licensed under both, <a href="http://www.wikipedia.org/wiki/GNU_Free_Documentation_License">GFDL</a> and <a href="GNU General Public License">GPL</a>. See <a href="http://textbook.wikipedia.org/wiki/Programming:Javascript">Wikibooks</a> </p> </body> </html>
Two Scripts
We are going back to the first example. But adding more to the script by also adding a different welcome message. This time a person is made to enter a name. They are also asked if they want to visit the site. Some CSS has also been added to the button.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>"THE BUTTON" - Javascript</title> <script type="text/javascript"> // global variable x x = 'You have not pressed "THE BUTTON"'; function bomb() { alert('O-GOD NOOOOO, WE ARE ALL DOOMED!!'); alert('10'); alert('9'); alert('8'); alert('7'); alert('6'); alert('5'); alert('4'); alert('3'); alert('2'); alert('1'); alert('!BOOM!'); alert('Have a nice day. :-)'); x = 'You pressed "THE BUTTON" and I told you not too!'; } </script> <style type="text/css"> body { background-color:#00aac5; color:#000 } </style> </head> <body onload="welcome()"> <script type="text/javascript"> function welcome() { var name = prompt('What is your name?', ''); if (name == "" || name == "null") { alert('You have not entered a name'); welcome(); return false; } var visit = confirm('Do you want to visit this website?') if (visit == true) { alert('Welcome ' + name); } else { window.location=history.go(-1); } } </script> <div> <input type="button" value="THE BUTTON - Don't Click It" onclick="bomb()" STYLE="color: #ffdd00; background-color: #ff0000"><br> <input type="button" value="Click Here And See If You Have Clicked ''THE BUTTON''" onclick="alert(x)"> </div> <p> This script is dual-licensed under both, <a href="http://www.wikipedia.org/wiki/GNU_Free_Documentation_License">GFDL</a> and <a href="GNU General Public License">GPL</a>. See <a href="http://textbook.wikipedia.org/wiki/Programming:Javascript">Wikibooks</a>, </p> </body> </html>
Simple Calculator
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>Calculator</title> <script type="text/javascript"> function multi() { var a = document.Calculator.no1.value; var b = document.Calculator.no2.value; var p = (a*b); document.Calculator.product.value = p; } function divi() { var d = document.Calculator.dividend.value; var e = document.Calculator.divisor.value; var q = (d/e); document.Calculator.quotient.value = q; } function circarea() { var r = document.Calculator.radius.value; pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756 48233786783165; var a = pi*(r*r); document.Calculator.area.value = a; var c = 2*pi*r; document.Calculator.circumference.value = c; } </script> <style type="text/css"> body { background-color:#00aac5; color:#000 } label { float:left; width:7em } </style> </head> <body> <h1>Calculator</h1> <form name="Calculator" action=""> <fieldset> <legend>Multiply</legend> <input type="text" name="no1"> × <input type="text" name="no2"> <input type="button" value="=" onclick="multi()"> <input type="text" name="product"> </fieldset> <fieldset> <legend>Divide</legend> <input type="text" name="dividend"> ÷ <input type="text" name="divisor"> <input type="button" value="=" onclick="divi()"> <input type="text" name="quotient"> </fieldset> <fieldset> <legend>Area and Circumfrence of Circle</legend> <p>(Uses pi to 240 d.p)</p> <div> <label for="radius">Type in radius</label> <input type="text" name="radius" id="radius" value=""> </div> <div> <input type="button" value="=" onclick="circarea()"> </div> <div> <label for="area">Area</label> <input type="text" name="area" id="area" value=""> </div> <div> <label for="circumference">Circumference</label> <input type="text" name="circumference" id="circumference" value=""> </div> </fieldset> </form> <p>Licensed under the <a href="http://www.gnu.org/licenses/gpl.html">GNU GPL</a>.</p> </body> </html>
Finding Elements
The most common method of detecting page elements in the DOM is by the document.getElementById(id) method.
Simple Use
Let's say, on a page, we have:
<div id="myDiv">content</div>
A simple way of finding this element in Javascript would be:
var myDiv = document.getElementById("myDiv"); // Would find the DIV element by it's ID, which in this case is 'myDiv'.
Anothere way to find elements on a web page is by the getElementsByTagName(name) method. It returns an array of all name elements in the node.
Use of getElementsByTagName
Let's say, on a page, we have:
<div id="myDiv"> <p>Paragraph 1</p> <p>Paragraph 2</p> <h1>An HTML header</h1> <p>Paragraph 3</p> </div>
Using the getElementsByTagName method we can get an array of all <p> elements inside the div:
var myDiv = document.getElementById("myDiv"); // get the div var myParagraphs = myDiv.getElementsByTagName('P'); //get all paragraphs inside the div // for example you can get the second paragraph (array indexing starts from 0) var mySecondPar = myParagraphs[1]
Adding Elements
Basic Usage
Using the Document Object Module we can create basic HTML elements. Let's create a div.
var myDiv = document.createElement("div");
What if we want the div to have an ID, or a class?
var myDiv = document.createElement("div"); myDiv.id = "myDiv"; myDiv.class = "main";
And we want it added into the page? Let's use the DOM again...
var myDiv = document.createElement("div"); myDiv.id = "myDiv"; myDiv.class = "main"; document.documentElement.appendChild(myDiv);
Futher Use
So let's have a simple HTML page...
<html> <head> </head> <body bgcolor="white" text="blue"> <h1> A simple Javascript created button </h1> <div id="button"></div> </body> </html>
Where the div which has the id of button, let's add a button.
myButton = document.createElement("input"); myButton.type = "button"; myButton.value = "my button"; placeHolder = document.getElementById("button"); placeHolder.appendChild(myButton);
All together the HTML code looks like:
<html> <head> </head> <body bgcolor="white" text="blue"> <h1> A simple Javascript created button </h1> <div id="button"></div> </body> <script> myButton = document.createElement("input"); myButton.type = "button"; myButton.value = "my button"; placeHolder = document.getElementById("button"); placeHolder.appendChild(myButton); </script> </html>
The page will now have a button on it which has been created via Javascript.
Changing Elements
In order to change an element, you use its argument name for the value you wish to change. For example, let's say we have a button, and we wish to change its value.
<input type="button" id="myButton" value="I'm a button!">
Later on in the page, with JavaScript, we could do the following to change that button's value:
myButton = document.getElementById("myButton"); //searches for and detects the input element from the 'myButton' id myButton.value = "I'm a changed button"; //changes the value
To change the type of input it is (button to text, for example) then use:
myButton.type = "text"; //changes the input type from 'button' to 'text'.
Removing Elements
You can remove elements in Javascript with ease.
The correct way
//get the element node element = document.getElementById("element"); //remove the element from the document document.removeChild(element);
This would remove the element with id 'element'.
Code Structuring
Links
Links
Non-wiki discussion forums:
Other web sites and blogs:
- ePanorama:JavaScript
- JavaScript Tutorials
- WebReference JavaScript tutorials
- Which of these is the real Gecko DOM reference? Gecko DOM Reference, or Gecko DOM Reference ?
- "About: Focus on JavaScript" from Stephen Chapman
- Learn Javascript
- JavaScript Tutorial at W3Schools
Here is a list of useful web resources:
- W3Schools.com's JavaScript Reference
- JavaScript Essentials - An online JavaScript book designed to provide web developers with everything they need to know to create rich, interactive and dynamic web pages using JavaScript.
- www.devguru.com
- JavaScript Tutorials from HTML Source
- www.quirksmode.org - over 150 useful pages for CSS and Javascript tips & cross-browser compatibility matrices.
- unobtrusive JavaScript - a guide on how to write JavaScript so that your site degrades gracefully (i.e., if the browser does not support or has turned off JavaScript, your site is still usable).
Useful Software Tools
Here's a list of useful tools for JavaScript Programmers.
- Notepad++ - A Great tool for editing any kind of code, includes syntax highlighting for many programming languages.
- Programmers' Notepad - A general tool for programming many languages.
- List of Really Useful Free Tools For JavaScript Developers