JavaScript

One of the three main languages of web pages:

  • HTML -- content
  • CSS -- presentation
  • Javascript -- behaviour

  • Developed in 1995 by Brendan Eich at Netscape
  • Initially called Livescript
  • 1996 renamed JavaScript
  • Has NOTHING to do with SUN’s Java
  • 1997 ECMAScript
  • Prefered name is JavaScript
  • 1999 ECMAScript 3
  • 2009 ECMAScript 5
  • Interpreted / Scripting language. Needs web browser, with it’s own internal javascript engine
  • Client side. Files are sent to and executed on the client browser (as opposed to server side)

Syntax

Javascript:

  • Is made up of statements contained with <script> </script> tags within an html page
  • The JavaScript statements tell the browser what to do
  • Is case sensitive!
  • Ignores whitespace (spaces, tabs, newlines)
  • Semi-colons are optional, but highly recommended
    • If omitted, new statements should appear on a new line
  • Comments, same as C/C++
    • //text after double forward slash
    • /* text between slash-star, across multiple lines */
    • recognises html comment <!-- as being the same as //
      • html closing comment --> is not recognised and should be written as //-->

 

This JavaScript uses document.write to output some simple HTML to the page, opens an alert box and display the rest of the HTML. Comments have been included to show various styles:

Save & refresh browser:

Welcome to your first JavaScript!

A JavaScript popup alert box will now appear!
followed by more text when you click OK on the popup…

Here’s some more text!

 

*note: running the above will initially display the first three lines of text and a popup alert box, followed by the final line when the OK button is clicked upon

<script> Element

To use JavaScript in a web page, the <script> element tags are used.

 

Strictly speaking, the TYPE attribute should be set to ‘application/javascript’, but since that doesn’t work in IE it is more common to either find ‘text/javascript’ or nothing.

 

You may also sometimes find // <![CDATA[ just after the opening <script> tag and its associated // ]]> just before the closing </script > tag. These commented out lines inform XHTML supporting browsers that the content of the script is character data and should not be interpreted as XHTML markup, and are generally not bothered with but is good to know just in case.

 

Save & refresh browser:

Javascript goes here!

<noscript> Element

If JavaScript is not enabled or the browser does not support JavaScript, a message can be displayed to the user using the <noscript> element, and is generally placed after the <script> tags, like so:

Save & refresh browser:

Please enable JavaScript, or try a JavaScript enabled browser.

Placement

JavaScript is executed by the browser at the first statement and moves down continuing to execute each statement as it comes to it.

 

Can be placed in:

  • <head> </head>
  • <body> </body>
  • <head> </head> and <body> </body>
  • External file, often append .js

 

Recommended to place at the end of the html just before the closing </body> tag, since this allows the browser to render the html in the page, and not be slowed up by a potentially long waiting bottleneck for a piece of JavaScript to finish before it renders the rest of the page.

 

General rule of thumb css at the top, JavaScript at the bottom.

 

 

<head>

This example, contained within<head> tags, will show that the browser pauses execution waiting for the OK button to be clicked until it continues rendering the rest of the page:

 

 

<body>

Whereas, this example will show the rendered page in the background and then executes the JavaScript pausing the browser wisitng for the OK button to be clicked:

 

 

Full Javascript code written within the html is referred to being inline (i.e. within the rest of the html code). Whilst this might be fine for small snippets, functions or testing purposes it is recommended for larger JavaScripts to use an external file. This also has the added benefit of allowing code reuse as other file might require access to it.

 

External file

Since the length and complexity of the JavaScript may be unwieldy, and potentially used by other pages, it is recommended to use an external files for your JavaScript.  To use an external file, the file’s source name is specified within the opening <script> tag’s src attribute

e.g.

<script src=”fileName.js”></script>

 

The preferred convention is to use a .js extension for JavaScript files.

 

Given this simple external javascript file:

This can now be called into the html file as follows:

*note: path is relative to calling file

Keywords

The following are keywords used in JavaScript and cannot be used for naming variables, functions, methods, labels, objects:

 

abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with

Variables

Named ‘container’ for a piece of computer memory that holds a specified value.

 

  • Variable names consist of letters, number, _, $
  • Cannot start with a number

 

Variables are declared by using the keyword var followed by the desired name. e.g.

var name ; //declaration of a variable, undefined

 

Variables with no value are Undefined.

 

 

Values can also be assigned to a variable (aka initialisation) using the = assignment operator:

var age = 42 ; //definition of a variable

 

Variables can also be emptied by assigning them to a value of null. e.g.  myCar = null;

 

 

Multiple variables can be separated with commas: var firstName, middleName, lastName ;

 

Which can also be multiply initiated at definition: var firstName = “Alan”, middleName = “Mathison”, lastName = “Turing” ;

 

JavaScript does NOT require the data type being specified.

 

var myNumber = 200 ; //integer

var myFloat = 3.14 ; //floating point number

 

Text strings needs to be quoted with single or double quotes but should not be mixed at start/end. However, a single quote could be used within a double quoted string as an apostrophe:

 

var mySeason = “It’s Spring again.” ; //double quotes used around a string of text characters. Note use of single quote allowed with double quotes

var myWeather = ‘My favourite weather is rainy!’ ; //single quotes used around a string of text characters

var myBool = true ; //a boolean could also be assigned false

Operators

Arithmetic a = 12, b = 4
+
--
*
/
%
++
– –
Addition
Subtraction
Multiplication
Division
Modulus
Increment
Decrement
a
a
a
a
a
a
a
+
--
*
/
%
++
– –
b
b
b
b
b
16
8
48
3
0
13
11

 

Assignment a = 12, b = 4
=
+=
-=
*=
/=
%=
Assign to
Add and assign
Subtract and assign
Multiply and assign
Divide and assign
Modulus and assign
a
a
a
a
a
a
=
+=
-=
*=
/=
%=
b
b
b
b
b
b
b now equals 12
a now equals 4
a now equals 8
a now equals 48
a now equals 3
a now equals 0

 

Comparison a = 12, b = 4
==
!=
>
<
>=
<=
Equality
Inequality
Greater than
Less than
Greater than or equal
Less than or equal
a
a
a
a
a
a
==
!=
>
<
>=
<=
b
b
b
b
b
b
false
true
true
false
true
false

 

Logical a = 12, b = 4
&&
||
!
And
OR
NOT
a
a
a
&&
||
!
b
b
b
true
true
!(a||b) = false
reverses condition

 

Conditional a = 12, b = 4
a > ? : Ternary a > b ? car : bike car 

 

 

typeof
Unary operator placed before a single operand (which can be of any type) and returns true or false based on an evaluation or a string indicating the data type of the operand.

 

Number “number”
String “string”
Boolean “boolean”
Object “object”
Function “function”
Undefined “undefined”
Null “object”

Save & refresh browser:

a is a number
b is a string

Dialogue Boxes

alert()

Very simply displays a popup alert box, with a single OK button:

alert(“Message goes here!”);

 

 

prompt()

Displays a prompt box, requesting text to be entered, which can be assigned to a variable:

 

 

confirm()

Displays popup confirmation box with OK and cancel buttons:

 

 

To get a new line in a dialogue box use the escaped \n sequence.

if, else, else if

Conditional statement to test if a condition is true of false.

 

Save & refresh browser:

42 is more than 17

switch case

Tests a condition against any number of case conditions.

 

Break must be used to terminate the switch, or the next statement will be executed.

 

A default case is utilised for when no condition is met.

 

This example asks the user to enter a value in a dialogue box and then checks it against the values in the switch case code block:

Save & refresh browser:

You entered 5

while

Loops through the statements enclosed within the { code block } until the test_expression is false:

 

while (test_expression) {
statements ;
}

 

Save & refresh browser:

val = 0
val = 1
val = 2
val = 3
val = 4

do

Loops through the statements enclosed within the { code block } until the following while test expression is false:

 

do {
statements ;
} while (test expression) ;

 

*note the ending semi-colon ; after the while test expression!

 

The do loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

Save & refresh browser:

val = 5
val = 6
val = 7
val = 8
val = 9

for

Iterates through the loop, starting from the specified initial condition and will iterate through the statements enclosed within the { code block } until the test is false. The initial condition, test and iterator are separated with a semi-colon ;

 

Syntax:

for (initialisertestiterator ) {

statements ;

}

 

 

Save & refresh browser:

val = 10
val = 11
val = 12
val = 13
val = 14

for/in

The for in loop iterates through an objects properties: 

Save & refresh browser:

Ducati
Panigale
1198

break

Terminates execution of the loop it’s running in.

 

This example has the val variable initialised to a starting value of 4 and checks in the for loop if the value has reached 7, if not carry on, otherwise break out of the loop:

Save & refresh browser:

val = 4
val = 5
val = 6
val = 7

continue

Passes control to the next iteration of the loop it’s running in, bypassing any remaining statements within that code block.

 

This example has the val variable initialised to a starting value of 4 and checks in the for loop if the value is greater than 6 AND less than 12, if not carry on, otherwise skip that iteration:

Save & refresh browser:

val = 4
val = 5
val = 13
val = 14

functions

A function is a block of code that is called using its function name.

 

Functions are declared using the keyword function, followed by the identifier aka token / function name and zero or more parameters to pass into the function within parentheses.

 

Syntax:

function myFunction(parameters){

…statements…

}

 

To use the function it is called by using the function name .e.g myFunction(parameters) ;

 

This example shows three functions. The first simply calls a function with no parameters. The second function is called with a single parameter (bike) that is passed in to the function, which also uses the global topSpeed variable. Finally the third function also passes in the topSpeed global variable but also returns a value that is used in the last statement:

Save & refresh browser:

If only I could afford one of these!
My Ducati Panigale R has a top speed of 202mph!
Spanking out 67.33mph in just the 1st gear!

Arrays

An array is a single variable that holds multiple values.

 

Denoted by square brackets e.g. var myArray = [ ] ;

 

Can use array index to insert values:

 

var myArray[0] = 17 ;

var myArray[1] = 22 ;

var myArray[6] = “Two-dimensional infrared spectroscopy” ;

 

  • Values can be of mixed data types.
  • Accessed through the index
  • 0 based index

To get the value use the square brackets with the desired index number of the value required:

 

var test = myArray[6] ; //test now has the same value as myArray index 6

 

 

Shorthand, enter values separated by comma:

 

var myArr = [21, 45,”Electron-Vibration-Vibration”]; //automatically indexed from 0

 

Alternatively, you may see an array declared as follows:

 

var myArr = new Array(); //since arrays are objects this creates an array as an object

 

 

Since arrays are objects (with properties and methods) they have information that we can access. For instance to find the length of an array we could use the .length property:

 

var myArr = [2013, “March”, “Start”] ;

document.write(myArr.length) ; //this would display 3

var reversedArr = myArr.reverse() ; //this new array now has the values reversed, equivalent to [“Start”, “March”, 2013] ;

 

Adding an item to an array

 

Simply specify the new index using the square bracket notation [N]. So assuming an array has 3 elements (starting from 0) the 4th element will be at index 3:

 

myArray[3] = ‘new-item’ ;

 

Alternatively, we can use the .length method of the array as the index of the last position:

 

myArray[myArray.length] = ‘new-item’ ;

 

Another approach is to use the .push() method with the new item within its parentheses:

 

myArray.push(‘new-item’) ;

myArray.push(‘new-item-1’, ‘new-item-2’, ‘new-item-3’) ;

 

All of the above approaches add the new item to the end of the array, whereas the .unshift() method allows the new item to be added to the front of the array:

 

myArray.unshift(‘new-item’) ;

 

 

Deleting items from an array

 

To remove the last element from an array, use the .pop() method:

 

myArray.pop() ; //e.g. original array [0,1,2,3] results in [0,1,2]

 

Or, to remove the first element in an array, use the .shift() method:

 

myArray.shift() ; //e.g. original array [0,1,2,3] results in [1,2,3]

Numbers

All numbers in JavaScript are 64bit floating point numbers.

 

Addition Vs Concatenation:

 

Addition
var a = 7 ;
var b = 8 ;
document.write(a + b) ; //treats as numbers, therefore = 15

 

Concatenation
var c = “6”;
var d = “9”;
document.write(c + d) ; //treats as strings, therefore = 69

 

If any part of statement contains a string, the whole statement will be treated like a string.

var e = 4;
var f = “13”;
document.write(e + f) ; //treats as strings, therefore = 413

 

NaN = Not a Number
If non computable values are used, JavaScript returns NaN.

var g = “Proteins”;
var h = 3;
document.write(g * h) ; //returns Nan

 

To overcome this the builtin Number(); //converts to a number if possible

var myNum = Number(g) ;

if (isNaN(myNum)){

document.write(“var i is not a number.”) ;

}

 

Math object

var  x = 200.6

var y = Math.round(x); //201

 

Math.max

Math.min

Math.PI

Math.rando()m

.sqrt()

.log()

 

Strings

  • Series of characters, strung together
  • Quotes are used to encapsulate a string
  • Can be single or double quotes
    • var myString = This is a string in double quotes ;
    • var myString = This is a string in single quotes ;
  • Cannot be mixed within the same statement
    • var myString = This will not work as expected since it has mixed quotes ;
  • If one or the other is required within a string it can be
    • escaped by using the backslash \
      • var myString = Escaping it\’s single quote with a backslash ;
    • Use the other quotes
      • var myString = Using a single inside its double quotes ;

 

Strings can also be treated as objects (with properties and methods) that have information we can access. For instance to find the length of a string we could use the .length property:

var myString = “Here’s a bunch of uninteresting text” ;

document.write(myString.length); //returns 36, including all characters and spaces

document.write(myString.toUpperCase()); //returns: HERE’S A BUNCH OF UNINTERESTING TEXT

 

.toLowerCase()

.split(” “) //passing in a space, to split string apart (in this case using a space) into an array

.indexof(“bunch”) //returns the index position of where the passed in term starts = 9

*note: if the term is not found it will return -1

.lastIndexOf(“te”) //returns the last index position of where the passed in term is found = 32

 

 

Slice

var myString = “Another mundane simple line of text!” ;

var mySlice = myString.slice(8, 15) ;//starting position from 0, up to (but not including) ending position = mundane

 

.substring(start, end) //same as above

.substr(start, length) //uses length as the number of characters to return

 

 

Comparison

Case sensitive

 

var string1 = “animal” ;

var string2 = “banana” ;

if (string1 < string2 ) {  //true

var string1 = “animal” ;

var string2 = “Banana” ;

if (string1 < string2 ) {  //false

 

Upper case letters are considered less than lowercase letters.

 

http://developer.mozilla.org/en/JavaScript/Reference

Dates

Dates are stored as the number of milliseconds from the Epoch 1 January 1970

 

To get the current date & time:

var today = new Date();

 

To set a date:

var special = new Date(1941, 1, 14);  //year, month (zero based!), day

 

Or even more precisely to the second:

var happy = new Date(1969, 10, 18, 11, 45, 23);  //year, month (zero based!), day, hours, minutes, seconds

 

 

Date object methods

 

today.getTime(); // returns the number of milliseconds since 01.01.1970

today.getDay(); // returns 0 -- 6 day of week, where 0 = Sunday

today.getDate(); // returns 1 -- 31 day of month

today.getMonth(); // returns 0 -- 11

today.getFullYear() // returns YYYY, not zero based

today.getHours(); // returns 0 -- 23

 

Example:

var today = new Date(1969, 10, 18);

today.getDay() ; //returns 2, indicating Tuesday

 

today.setMonth(2) ; // sets the month to March

today.setFullYear(1980) ; // sets year to 1980

today.setDay(0); // sets day to Sunday

 

 

Comparing Dates

 

var date1 = new Date(1969, 10, 18);

var date2 = new Date(1969, 10, 18);

 

if ( date1 == date2) { //returns false, because they are not the same OBJECT

 

if ( date1.getTime() == date2.getTime()) { //returns true, because the .getTime() method returns the milliseconds

Objects

An object is an abstract data type that contains properties and methods.

 

  • Properties are its values
  • Methods are its internal functions

 

Although JavaScript is object oriented, it does not use classes to create objects. The reason being that it is prototype based, not class based.

 

Objects can be created by:

  1. Defining and creating a direct instance of an object
  2. Using a function to define an object, then create new object instances from that function

 

1. Creating a Direct Instance

 

This example creates a new instance of an object using the keyword new and then assigns three properties using the dot operator:

var rider = new Object();

rider.name = “Marquez”;

rider.team = “Honda”;

rider.pos = 1;

 

Alternatively, the shorthand (using object literals) allows you to specify name: value pairs within {curly braces}. Notice the colon, after the name:

e.g.

var rider1 = {name: “Marquez”, team: “Honda”, pos: 1} ;

var rider2 = {name: “Lorenzo”, team: “Yamaha”, pos: 3} ;

 

Unlike other more formal object oriented languages, JavaScript is much looser and an object’s methods need to be associated via a prototype. Say a function was declared like so:

 

function displayMe() {

document.write(name + ” rides for ” + team + ” and is currently ” + pos + ” in the world championship!<br>”);

}

 

We then create a prototype to associate the function to the object, like so:

 

rider1.showMe = displayMe ;

 

Notice how the function hasn’t been called (since no parentheses were used), as it is just being associated to the rider1 object.

 

However, this would not work since the function does not know which object is calling it, and which values it should use. Therefore the keyword this is used within the function to refer to the current calling object:

 

function displayMe() {

document.write(this.name + ” rides for ” + this.team + ” and is currently ” + this.pos + ” in the world championship!<br>”);

}

Now we can use the function as a method of the calling object:

 

rider1.showMe();

 

Notice the parentheses are now being used to indicate the method should be called.

 

Save & refresh browser:

Marc Marquez rides for Honda and is currently 1 in the world championship!
Jorge Lorenzo rides for Yamaha and is currently 3 in the world championship!

 

 

2. Using an Object Constructor function

 

This technique is closer to that of other object oriented languages, although the class keyword is not used.

 

function rider(name, team, pos) {

this.name = name ;

this.team = team ;

this.pos = pos ;

}

 

The above object constructor can now be used to create objects:

 

var rider1 = new rider(“Marc Marquez”, “Honda”, 1);

var rider2 = new rider(“Jorge Lorenzo”, “Yamaha”, 3);

 

Methods can also be added to the constructor function:

 

function rider(name, team, pos) {

this.name = name ;

this.team = team ;

this.pos = pos ;

 

this.changePos=changePos;
function changePos(newPos) {

this.pos=pos;

}

}

 

 

 

Save & refresh browser:

Marc Marquez rides for Honda and is currently 1 in the world championship!
Jorge Lorenzo rides for Yamaha and is currently 3 in the world championship! 

 

Now let’s change their positions.
Marc Marquez rides for Honda and is currently 2 in the world championship!
Jorge Lorenzo rides for Yamaha and is currently 4 in the world championship!

Document Object Model

A formal definition: The DOM is a cross platform, language independent, API for HTML, XHTML and XML documents that allows programs and scripts to dynamically access and change the style content and structure of a document.

 

Or: The DOM is a model (structure) of the objects (nodes) for a web page (the document) that provides a standard method of showing how a web page is made up, that can be used on any machine using any browser it chooses, allowing scripts to be able to manipulate how the page looks and behaves.

 

 

Browsers include a JavaScript engine (interpreter) that recognises standard instructions that allow access to the nodes (objects) of the webpage (document).

 

Whenever a web page is loaded by browser, its JavaScript engine creates a DOM of that page as a number of node objects.

 

Of the twelve node types, the three main nodes we’re interested in are:

  • The ELEMENT node
    • html tags e.g. <body>, <h1>, <p>, <ul>, etc.
  • The ATTRIBUTE node
    • tag attributes within an elements < angled brackets> e.g. class=”myClass”, id=”myId”, style=”myStyle”, etc.
  • The TEXT node
    • This is the actual text content between the opening and closing tags e.g. <p>This is the text content node</p>

 

The DOM for a web page can easily become very large. Given a very simple html file:

 

The DOM can be depicted as follows:

 DOM nodes 

 

The above image represent all nodes for the above html, and can be broken down as follows:

  • The ELEMENT node
    • Node.ELEMENT_NODE == 1

Element node

  • The ATTRIBUTE node
    • Node.ATTRIBUTE_NODE == 2

Attribute node

  • The TEXT node
    • Node.TEXT_NODE == 3

Text node

 

The node types can be accessed by JavaScript using the .nodeType method. For example:

Save & refresh browser:

The body element returns a node type value of: 1

.getElementById();

To access a unique element the .getElementById(); method should be used.

 

var myElement = document.getElementById(“myId”); //assigns a handle to the node containing id=”myId”

 

 

This example assigns the element with an id of myHeading to a variable (handle) and then displays the text (using innerHTML) within that element:

Save & refresh browser:

An h1 tag element with an id of myHeading

An h1 tag element with an id of myHeading

.getElementsByTagName();

To access an element of a particular type the .getElementsByTagName(); method should be used.

 

var myElement = document.getElementsByTagName(“p”);  //returns an array of all found elements

 

If no element is found the returned array will be empty.

 

Specific returned elements can be accessed using square bracket array [ ] index notation (starting from 0).

 

e.g. if there were 7 <p> elements in the document, the 2nd could be accessed like so:

 

myElement[1]

 

 

If a large number of elements were found it might make it tricky to home in on a specific target element and therefore a combination of .getElementById(); and .getElementsByTagName(); could be used together. e.g. say the .getElementsByTagName(); returned a large number of <p> elements and you only wanted to access those under a certain div, assuming the div had an id attribute, then a new variable could be assigned to that div and then the same .getElementsByTagName(); method can be applied to the new variable, like so:

 

var myParas = document.getElementsByTagName(“p”);  //gets all <p> elements

var myDiv = document.getElementById(“theDivId”) ; //assigns variable handle to target dive

var divParas = myDiv.getElementsByTagName(“p”); //target div now has .getElementsByTagName(); method applied

 

Now, just the <p> elements within the target div are assigned to a variable based on the target div.

 

This example illustrates the above technique using JavaScript to display the <p> elements in the div with id=”myDiv”. I’ve also used css to set the display:none, and then let JavaScript display the found text:

Save & refresh browser:

Using JavaScript to extract just the text within the p tags of myDiv:
First line of text.
Second line of text.
Third line of text.

 

 

 

Just placing a few reminders here for the time being…

Node.nodeType //returns 1 for an element, 2 for an attribute, 3 for a text node
Node.innerHTML //returns text inside element tags
Node.childNodes //returns array of child nodes
Node.childNodes.length //returns length of array of childNodes

Changing Elements

To get an attribute of an element the .getAttribute(); method can be used:

 

myElement.getAttribute(“color”); //passing in the desired property to get within quotes

 

Similarly, to set an attribute for an element the .setAttribute(); can be used:

 

myElement.setAttribute(“color”, “red”); //passing in the desired property followed by the value to set within quotes

 

*note: if an attribute doesn’t already exist for that element, it will be created

 

We’ve also already seen that the .innerHTML method can be used to change the text within an element.

 

 

An alternative approach could use the style method:

 

document.getElementBtId(“myElement”).style.color = “#0000FF” ;

 

Which is equivalent to:

 

var myElement = document.getElementBtId(“myElement”) ;

var myElementSytle = myElement.style ;

 

So now, myElementStyle can be directly used to set the css styling for the specified element:

 

myElementStyle.margin = “5px 0 10px 7px” ;

myElementStyle.color = “blue” ;

myElementStyle.border = “solid 2px red” ;

myElementStyle.paddingBottom = “2em” ;

 

*note: the use of camelCase instead of a hypen as in normal css being padding-bottom, we use paddingBottom

 

Since an element’s properties can be accessed as though in an array, we can take this further and create a function that would work upon a passed in element and it’s desired property and value to change:

Save & refresh browser:

Here’s my heading

Using JavaScript to change the properties of an element!

 

Perhaps the above style changing function isn’t the most useful of functions since it’s probably easier to simply write:

myElement.style.textDecoration = “underline”;

but this approach shows another way of changing an element.

Creating Elements

To create an element:

  1. Create the element, using the .createElement() method
  2. Add text (if required), using either the .innerHTML or .createTextNode() method
  3. Add it to the DOM, using the .appendChild() method

 

var newElem = document.createElement(“p“) ; //passing in the type of element as a string in quotes

 

At this point the newly created element is empty and not attached to the DOM.

 

Therefore to add content to the element, we can either use:

 

.innerHTML method:

 

newElem.innerHTML = “Text for newly created element.” ;

Now the new element has content it can be attached to the DOM, using the appendChild() method to add it to an existing element:

myExisting.appendChild(newElem) ;

 

Or the more ‘correct’ approach of adding a text node:

 

var newText = document.createTextNode(“Text for newly created element.”) ;

newElem.appendChild(newText) ;

 

Again, this is not associated with anything and therefore has to be attached to the target element using the appendChild() method:

 

myExisting.appendChild(newElem) ;

 

 

Example showing above approaches to create new elements:

Save & refresh browser:

Using Javascript to create new elements.

A shiny new h2!

Here’s a new paragraph.

.insertBefore()

An alternative approach to the appendChild() method is to use the .insertBefore() method, as follows:

 

  1. Create the new element, using the .createElement() method
  2. Create a handle to the required insertion point
  3. Use the .insertBefore() method to insert the new element (from 1) before the handle (from 2)

 

Taking the above we therefore have:

 

var newElem = document.createElement(“li”) ;

var sixthLi = myExisting.getElementsByTagName(“li”)[5] ;

myExisting.insertBefore(newElem, sixthLi) ;

 

 

This example shows an ordered list of ten items, using the .insertBefore method to insert a new element before the sixth list item:

Save & refresh browser:

  1. First list item
  2. Second list item
  3. Third list item
  4. Fourth list item
  5. Fifth list item
  6. THIS IS THE NEWLY INSERTED LIST ITEM
  7. Sixth list item
  8. Seventh list item
  9. Eighth list item
  10. Ninth list item
  11. Tenth list item

 

 


.insertAfter()

 

Although there its no insert after method, a function can be created to simulate this as follows:

Save & refresh browser:

  1. First list item
  2. Second list item
  3. Third list item
  4. Fourth list item
  5. Fifth list item
  6. Sixth list item
  7. THIS IS THE NEWLY INSERTED LIST ITEM
  8. Seventh list item
  9. Eighth list item
  10. Ninth list item
  11. Tenth list item

Traversing the DOM

Traversing the DOM is the term used to describe the act of finding and selecting nodes within a web page.

 

Various properties enable the selection of nodes that can be used to move within a document.

 

Node.childNodes Returns an array of all child nodes of the specified parent node
Node.firstChild Equivalent to the first item in the ‘childNodes’ array (‘Element.childNodes[0]‘)
Node.lastChild Equivalent to the last item in the ‘childNodes’ array (‘Element.childNodes[Element.childNodes.length-1]‘)
Node.parentNode Provides access to parent node of specified node.
Only one parent node.
Grandparent would be accessed by ‘Node.parentNode.parentNode’
Node.nextSibling Provides access to next node on the same level within the DOM tree.
Node.previousSibling Provides access to last node on the same level within the DOM tree.

Events

An event is the result of an action being carried out by the user or the browser caused by something they have done on the web page, be that a mouse movement, a button click, scrolling down, etc.

 

Some of the more common events are:

Mouse Events
onclick mouse click
ondbclick mouse double click
onmouseover mouse pointer over element
onmouseout mouse pointer moves out of element
onmousedown mouse button clicked
onmouseup mouse button released
onmousemove mouse pointer moved
Keyboard Events
onkeydown key press
onkeyup key release
onkeypress key pressed & released
Form Events
onchange form element change
onsubmit form submitted
onreset form reset
onselect form element selected
onblur form element lost focus
onfocus form element focus
Frame Events
onload document, frame or object load
onunload document, frame or object unload
onscroll document scroll

 

These events can be acted upon by the use of event handlers (/listeners) that then carry out a specified action.

 

3 approaches:

  • Inline event handling
  • Event handling functions
  • Event listeners

 

Inline

Placing the JavaScript inline within the HTML:

 

Event handling functions

Using a function that is called upon the event being triggered for the element:

 

Using an event handler on the DOM element which is then assigned to an anonymous function. An anonymous is being used since there’s no need to name the function as it will only be carried out when the specified action occurs for that element, in this case onclick: 

*note: use of semi-colon at end of anonymous function, due to this being a statement piece of code.

 

 

Event listeners

Requires 4 pieces of information:

  1. The DOM element
  2. The event as a string without ‘on’
  3. The function to be run
  4. Event capture, boolean value set false 99% of the time – optional, only required for advanced event handling

 

This example shows two approaches, the first using a traditional function call, and the second using an anonymous function within the statement:

.onload

It is common place to place the JavaScript (preferably in a link to an external file) at the bottom of the page. However, there may be times when the code needs to placed before the html content, but this can cause an issue since the JavaScript  may be setting values that cannot be recognised by the script as the page contents, and therefore any elements, have not been loaded.

 

To overcome this issue, the .onload method can be called upon the window (top level browser object) which can be assigned to an anonymous function that calls any specified named functions upon the whole contents of the window (i.e. the document) being loaded:

*note: window.onload should only be used once within a page

.onfocus .onblur

Theses events can used to provide helping text within a form’s field elements that is activated when the user clicks or tabs to a specific form field element .onfocus,  or moves out of the form field element .onblur

 

Form example showing .onfocus and .onblur

Timers

Allows JavaScript to be run at specified times.

 

setTimeout()

Runs once.

Requires:

  • Name of function to run
  • Duration in milliseconds

An alert is shown after 3 seconds:

 

setInterval()

Repeats specified function at the specified interval duration.

Requires:

  • Name of function to run
  • Duration in milliseconds

Initial image is shown, and then changed to the next array index value every 3 seconds:

 

 

clearTimeout() and clearInterval() are the complementary functions of the above setTimeout() and setInterval() functions, that allow us to clear the previously set timers.

 

For example, setInterval() also returns a value which we can store in a variable, which we can then use within the clearInterval() function. This example uses the onclick event to clear the setInterval timer and hence stop the images changing:

.location

The .location method can be used to redirect or return information about the current location.

 

Redirect

To redirect assign the target page to the window.location() function, like so:

 

window.location = “http://www.motogp.com“; //note use of assignment, not parentheses

 

To redirect a page straight away:

 

Or to call from a function, which could then be used in a setInterval():

 

 

Return values

.location can also be used to return values:

.navigator

The .navigator object contains information about the visitor’s browser:

Save & refresh browser:

Browser Info:

Browser CodeName: Mozilla
Browser Name: Netscape
Browser Version: 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36
Cookies Enabled: true
Platform: Win32
User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36
User-agent language: undefined

Cookies

Cookies are small text based files that are sent from a website and stored locally by the users browser. They are required because HTTP has no way to keep track of a user’s activity (i.e. stateless).

 

They have a maximum size of 4KB, for all attributes (e.g. name, key/values pairs)

 

Cookies can be used for various purposes from storing the user’s name to their last visit.

 

Cookies have a very specific format that must be adhered to, and cannot include white space, semi-colons or commas.

 

They consist of several name/value pairs that are separated by a semi-colon.

 

The key/value is separated with an equals sign.

 

An optional expiration can be included, after which time it’s deleted. If there’s no expiration date, the cookie is deleted at the end of the session, or when the browser is closed.

 

Date has to be in UTC/GMT format.

 

Domain and Path can be specified where the cookie can be read / written. Default path is ‘/’ (meaning visible to all paths in the domain), and if no path is specified it will belong to the page that set the cookie

 

The specific order for setting a cookie should be:

  • Name-value pair containing the actual data
  • Expiry date after which it is no longer valid
  • Path within the domain
  • Domain of the server it should be sent to

name-value;expiration_date;path;domain;

 

 

To create, read and delete cookies the document.cookie method is used:

 

document.cookie = “lastVisit=Thurs, 02 Aug 2013 09:53:00 GMT; expires=Thurs, 09 Aug 2013 00:00:00 GMT;”;

document.cookie = “userLevel=novice;”

 

Use the console with the following to see the result:

 

console.log(document.cookie);

 

 

To delete a cookie, simply set its date in the past.

 

This example has three functions to create, read and delete cookies. Two cookies are created and two buttons trigger the read and delete functions:

Excellent in depth article

console.log

Use console.log to provide diagnostic capabilities for debugging.

 

console.log(“Hello, world!”) ; //will print Hello, World! in the console

 

Other parameters can be passed in, such as document.cookies to show what cookies are currently used by the document, or passing a variable that has been assigned getElementsById:

 

var = myVar.getElementsBtId(“p”) ;

console.log(myVar) ;

 

This will return an array of all the p elements, that can further be drilled down into within the console.

 

Once in the console, you can use JavaScript as per your scripts, e.g. to make all text blue:

 

document.body.style.color = “blue”

Animation

Animation effects can be created to move objects around the document

 

This example has a div with a few lines of html, that is styled by JavaScript, and then moves across the page upon the window loading and .onclick:

Change Image onMouseOver

Simple script to change the image when the mouse pointer moves over the image and then back when out: