Introduction to Javascript

Introduction::

JavaScript brings dynamic functionality to websites. Every time you see something pop up on the page when the mouse is over an item, see new text, colors or images appear on the page – or are given the possibility to “grab” an object on the page and drag it to a new location – all those things are done with JavaScript. – It offers effects, interactivity and functionality that would otherwise not be possible, as it is a client-side scripting language which runs inside the browser and has direct access to all elements in a web document.
JavaScript first appeared as a new scripting language in the Netscape Navigator browser in 1995 – and has nothing to do with the Java Programming language…

Include JavaScript into your website:

In this section we look at the rules that must be followed to write properly structured and executable code.
All JavaScript code goes within the opening:<script> and closing </script> HTML tags.

A first JavaScript example:
Create a new html page: save it as index.html – or whatever you like in a local directory on your machine (i.e in a folder called Workshop Examples on your desktop). Copy and save the following example and run it in your browser.

1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<html> 
<head> 
<title>Hello world example in javascript</title> 
</head> 
<body>
<script type = "text/javascript">
document.write("Hello World");
</script>
</body>
</html>

Within the <script> tags is a single line of JavaScript code. document.write() is a custom JavaScript command which effectively outputs anything within the parentheses to the browser.

In addition to placing a script in the body of a document, you can also put it in the <head> section. The location of the JavaScript code, (i.e within the head or body tags) is the default location where JavaScript will write to.

The following example demonstrates this: specifically we see that depending on where the JavaScript is called the output location changes. This example also demonstrates that we can include any standard html tags within the document.write() command.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!doctype html>
<html> 
<head> 
<title>Hello world example in javascript</title> 
<script type = "text/javascript">
document.write("<h1>Hello World in the Head tag</h1> <br \>");
</script>
</head> 
<body>
<p> Here we have a really long paragraph... </p>
<script type = "text/javascript">
document.write("<h2>Hello World in the Body tag</h2><br \>");
</script>
<p> Here we have <b>another</b> really long paragraph... </p>
</body>
</html>

You can also include external JavaScript files either from your own personal web directory or anywhere on the internet. The syntax for this is:

1
<script type = "text/javascript" src ="script.js"></script>

or from somewhere on the internet:

1
<script type = "text/javascript" src ="http:// someServer.com/script.js"></script>

These script files must not include any <script> tags, because they are unnecessary: the browser already knows that a JavaScript file is being loaded.

Debugging JavaScript:

JavaScript errors are handled by the browser. Most browsers offer the functionality to debug and access JavaScript error messages in the associated error console.

  • In Safari: Enable the error console by Safari -> Preferences -> Advanced and checking the “Show Develop menu in menu bar”.
  • In Chrome A: Right click on the page, from the sub menu select Inspect. Activate the console tab.
  • In Chrome B: Click the customize button (rows of lines), then select More Tools -> Developer.
  • In Internet Explorer: Select Tools -> Internet Options-> Advanced, then uncheck the “Disable script debugging” box and check the “Display a notification about every script error” box.
  • In Firefox: Select Tools -> Web Console.
  • In Opera: Select Tools -> Advanced -> Error Console.

Try out the error console with the following example which contains a simple error:

A first JavaScript example with an error:

1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<html> 
<head> 
<title>Hello world example in JavaScript</title> 
</head> 
<body>
<script type = "text/javascript">
document.write("Hello World)
</script>
</body>
</html>

Question: How would we fix the error??

We can also debug the output from a JavaScript program by using the following inbuilt javascript method:console.log() . This method is similar to the println() statement in Processing – it will write out all the parameters that you supply within the parentheses. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!doctype html>
<html> 
<head> 
<title>Hello world example in JavaScript</title> 
</head> 
<body>
<script type = "text/javascript">
document.write("Hello World");
console.log("Hello World in the console");
 
</script>
</body>
</html>

JavaScript: Variables & Data:

Storing data so we can use it later is one of the most important purposes for writing code. Fortunately, JavaScript can do this… If it couldn’t, it’d be rather useless…
As a small exercise let’s ask the user (that’s you) for their surname…

  • Create a new html page and copy the following:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    <!doctype html>
    <html> 
    <head> 
    <title>Hello world example in JavaScript</title> 
    </head> 
    <body>
    <script type = "text/javascript">
    var surname = prompt('Hello, Please type in your surname and press ENTER');
    </script>
    </body>
    </html>
  • Now, if you load the page – a special “widget” gets launched by the JavaScript inbuilt command the prompt(). Basically – A little box will pop-up, asking for your surname. Type your surname in and hit OK.
  • The surname you entered is now saved, and it can be referred to as surname. You can get what you entered back out again by using the document.write() command.
    Place the following statement AFTER the prompt() command in your HTML page:

    1
    
    document.write("Surname given ::"+ surname);
  • Now when you load the page – after pressing ENTER – the surname should appear on the page…
    You’ve just created a variable.

Variables
Think, if you will, of a variable as a “location” with a name so it’s easy to get back to. You’ve just named a location to be surname. You can name a variable anything you like, but it’s best to name it in a way that tells what you’ve stored there. For example, surname is better than “mything” or “s”….

Consequently, When you type a variable name into the document.write() command, you are asking the browser, which maintains these locations, to go find that particular location and give whatever is at that location to you. This is also known as the variable’s value. The value can be almost anything – in surname, you’ve stored some letters, known as a string.. You can also store numbers and a myriad other kinds of data.

JavaScript is a “loosely typed” or “dynamic” language, meaning you don’t have to declare the types of variables ahead of time. The type will get determined automatically while the program is being processed. Other languages such as Java are strictly typed and each variable must declare the type of the data it will contain. Even though you don’t have to declare types, JavaScript does have different data types.

Creating a variable:
There are two parts to creating a variable: declaration & initialization . Once it’s created, you can assign (or set) its value.

  • Declaration:: is stating that a variable should exist. It’s like choosing a location and then giving a name to it. As in the example above: to declare a variable, use the var keyword followed by the variable name, like this: (Remember:: if you are trying out the following – please put it within script tags into your html file)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    var name = "Tom";
    // "Tom" is a string - a collection of letters. A string is surrounded by single or double quotation marks.
    // we can also use the inbuilt "length" method to find out the length of the variable 'name'
    var nameLength = name.length;
    var age = 20;
    //20 is just a number - and numbers don’t go in quotes.
    // lets output the "values" of the variables:
    document.write(name+"<br\>");
    document.write(nameLength+"<br\>");
    document.write(age+"<br\>");

There are quite a few other inbuilt JavaScript string methods (i.e substring(), toLowerCase(), toUpperCase() …). Other datatypes supported by JavaScript include floats, booleans(true or false), objects and arrays…

Variable Assignment:
The value of a variable with no value is undefined.
Also, variables can be emptied by setting the value to null.

As mentioned above, you can set a variable’s value as many times as you like. This process is called assignment and it looks very similar to initialization. You again use the equals sign, but there’s no need for the var keyword because we’ve already declared the variable.
Note: Only do this if you’ve already declared the variable using the var keyword!
Add the following after the document.write() commands –

1
2
3
4
5
6
name = "Andy";
age = 43;
// lets use another string method; "indexOf()" which will return the position of a given letter in the string
document.write(name+"<br \>");
document.write(name.indexOf("n")+"<br \>");
document.write(age+"<br \>");

What is important to note in this example is that the JavaScript is read from top down – so in the first two document.write() commands, the initial values for name and age are used – then we change the values (reassign), so consequently in the next two document.write() commands the new values are used.

JavaScript: Doing Simple Math:

Variables can be used to store strings and numbers (amongst other things), and when a variable is a number we can do some math::

Let’s create two variables. One will be the number of apples we have, the second will be the number of pears:
Add the following after the last document.write() in your html page::

1
2
3
4
5
document.write("<br \>");
var apples = 5;
var pears = 10;
document.write("Number of apples: "+ apples+"<br \>");
document.write("Number of pears: "+ pears+"<br \>");

Now, we will use these two variables to figure out how many pieces of fruit there are in total. Add the following statements to your HTML page::

1
2
var totalFruit = apples+pears;
document.write("Total Fruit: "+totalFruit+"<br \>");

What have we done? We have “asked” the browser to work out the sum on the right before assigning the result to the variable “totalFruit”.
Also we are not adding the variable names: – rather we are adding the values of the variables. The browser knows that, so when it sees a variable like this, it knows that you want to do something with the value. Therefore, it goes and gets each variable’s value before doing the sum.
The sum is called totalFruit, not “total fruit”. Variable names cannot contain spaces! There’s a set of rules on the web about what you can and can’t use in terms of conventions for naming variables, but for now just use letters with no spaces…

We can also do subtraction, division, multiplication in much the same way:::

1
2
3
4
5
6
7
8
var splitFruit = totalFruit/3;
document.write("Split Fruit (/3): "+splitFruit+"<br \>");
 
var subFruit = pears - apples;
document.write("Sub Fruit: "+subFruit+"<br \>");
 
var multiplyFruit = apples*pears;
document.write("Multiply Fruit: "+multiplyFruit+"<br \>");

Precedence & operators
For doing sums – as we have seen you can use various symbols: +, -, / and * .
Mathematical symbols are called operators – that is, they operate on some data. We’ll meet even more operators later on, but you should know that, like on a calculator, the symbols are worked out in a particular order, called operator precedence:

  1. Parentheses
  2. Multiplication
  3. Division
  4. Addition
  5. Subtraction

Here’s an example, stepping through how the browser runs it:

(10 + 2) / 2 + 4 * 2

1: The part in brackets is worked out first. So this becomes:
12 / 2 + 4 * 2

2: which works out to:
6 + 4 * 2

3: Then things are done in operator precedence order. If multiple sums are of the same precedence then they are evaluated left to right. The multiplication is higher precedence so is done first, which works out to:
6 + 8

This is used to work out the final value:
14

JavaScript: Logic:

The next example will illustrate a very important part of programming: using logic:
We want to be able to compare values in order to make decisions in code.
When a comparison is made the outcome is either true or false; a special kind a of data value called a boolean. This is logic.
Like when doing math, there exists a set of operators that work on booleans.
They are used to compare two values, on the left and right side of the operator, to produce a boolean value (true or false).
We have the following operators to perform comparisons:

  • Equality: if we wanted to find out whether two values are equal, use the == operator. i.e “15.234 == 16.234” – would be equated to false.
  • InEquality: if we wanted to find out whether two values are not equal, use the != operator. i.e “15.234 != 16.234” – would be equated to true.
  • Greater Than: if we wanted to find out whether the left value is greater than the right value, use the > operator. i.e “15.234 > 16.234” – would be equated to false.
  • Less Than: if we wanted to find out whether the left value is less than the right value, use the < operator. i.e “15.234 < 16.234” – would be equated to true.
  • Combined Comparisons: if we wanted to find out whether the left value is less than or equal the right value, use the <= operator. i.e “15.234 <=16.234” – would be equated to true.(Note the same idea applies to the greater than or equal comparison)

So given that we now understand how to make “boolean expressions” – how can these be used in the process of decision making? This requires using something called a conditional. There are a few different conditionals that you might want to use, but we’ll just focus the one used most commonly: if.
It is very simple: if some logic (the condition) is true then run a block of code.
You can also supply more code to be run if the condition is not true, and supply additional conditions and blocks of code to optionally be run. These forms are called if-else, as you’ll see below.
The most simple if statement looks something like this:
if (10 > 5)
{
// Run the code in here
}

The code between the braces – “{” and “}” – is called a block, and this one is linked to the if statement. It’s only run if the conditional (between the parentheses) is true.::: 10 is indeed greater than 5, so the code in the block would run.


The if-else form of an if statement is used to run an alternative piece of code if the conditional is not true. The code in the if block below will be ignored, for example – only the code in the else block will be run.
if (43 < 2)
{
// Run the code in here
} else
{
// Run a different bit of code
}

Now we are ready to implement such decision making in javascript: so copy the following into your html page: what is the output?
Logic Example:

1
2
3
4
5
6
7
8
9
10
11
12
var valOne =34;
var valTwo =50;
// use if /else construct to execute the correct statement
// condition test using less than operator
if (valOne<valTwo)
{
  document.write( "valOne is less than valTwo");
}
else
{
  document.write("valOne is greater than valTwo");
}

Functions

The write() in the “document.write()” expression is a built in javascript function. There are many inbuilt JavaScript “functions” – and we will soon see that we will also be able to create our own. But first what is a function?::
A function is a reusable block of code that carries out a specific task. To execute or “run” the code in a function you need to call it. A function can be passed arguments to use, and a function may return a value.
Lets start by creating a function: the following example defines a function which takes two numbers, adds them together and returns the result.

1
2
3
4
5
function add (a, b) 
{
   var c = a + b;
   return c;
}
  • Use the function keyword to specify that we are creating a function.
  • We give a “name”(like a variable name) to the function called “add” – we could have chosen any name.
  • The definition of the function is everything within the “curly braces”
  • a and b are the function’s “parameters”: the numbers which you want to add together.
  • The value that the function returns is signified by the “return” keyword. The return keyword also stops execution of the code in the function; nothing after it will be run.

So – how do we call a function? By specifying the name of the function: i.e. “add” along with the parameters needed. In this case there are two.
So if we add the following to our test html page:

1
2
3
4
document.write("<br \>");
var result = add(1, 2); 
document.write(result);
// result is now 3

Exercise: Write a function called “multiply” which takes two numbers and returns the product. Then write the command to call the function i.e. multiply(3,6); and use document.write() to output the result to the html page.

Variables & Scope in JavaScript
An important property of functions is that the variables created inside of them, including their parameters, are local to the function.
For example, given the following function definition :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function power(base, exponent) 
{
   var result = 1;
  for (var count = 0; count < exponent; count++)
  {
    result *= base; 
  }
  return result;
 
}
document.write(power(2,3));
//returns 8 (2*2*2)
document.write("<br \>");
document.write(power(3,4));
//returns 81 (3*3*3*3)

In this example, the result variable will be newly created every time the function is called, and these separate “contexts” do not interfere with each other.
This “localness” of variables applies only to the parameters and to variables declared with the var keyword inside a function body.
Variables declared outside of any function are called global, because they are visible throughout the program. It is possible to access such variables from inside a function, as long as you haven’t declared a local variable with the same name.

The following example demonstrates the use of global vs local variables. It defines and calls two functions that both assign a value to the variable x. The first one declares the variable as local and thus changes only the local variable. In contrast, the second function does not declare x locally, so the references to x inside of it refer to the global variable x defined at the top of the example…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!doctype html>
<html> 
<head> 
<title>Variables and Scope</title> 
</head> 
<body>
<script type = "text/javascript">
 
var x = "var x outside";
// function declarations
 function f1() 
{ 
   // re-declare a local var called x
   var x = "var x inside f1";
   document.write("Am inside f1():: x is  "+x);
   document.write("<br />");
}
function f2() 
{ 
   x = "x reassigned inside f2";
}
 
 // call our functions :)
f1(); 
document.write(x); 
// prints "var x outside"
document.write("<br />");
 
f2(); 
document.write(x);
document.write("<br />");
// prints "x reassigned inside f2"
</script>
</body>
</html>

Distinction to remember between local and global vars:

  • Global variables live as long as your application lives.
  • Local variables have short lives. They are created when the function is invoked, and deleted when the function is finished.

More on functions::
So far – we have defined functions using Function Declarations. They are parsed at pre-execution stage, when the browser prepares to execute the code.That’s why the function declared this way can be called both after and before the definition. For example: both of the following examples will work:

1
2
3
4
5
6
function sayHi(name) 
{
  document.write("Hi, "+name);
}
 
sayHi("Sabine");
1
2
3
4
5
6
7
 
sayHi("Sabine");
 
function sayHi(name) 
{
  document.write("Hi, "+name);
}

Also – a function can be declared anywhere in the script. For example, we may want to declare a function differently, depending on the condition:

1
2
3
4
5
6
7
8
9
10
var val =4;
if (val==2) 
{
  function sayHi() {  document.write("choice A"); }
} 
else 
{
  function sayHi() {  document.write("choice B");  } 
}
 sayHi();

Note with this example: we must have our test before calling the function – meaning that if we put the statement sayHi() before the condition, javascript would complain that it has no idea what sayHi() is….

Now – in JavaScript, we have another way that we can define functions: by Function Expressions. In JavaScript, a function is a first-class value, just like a number or string. Anywhere where you could put a value, you can also put a function, declared “at place” with a function expression syntax:

function(arguments) { … }.

For example, you can do:

1
2
3
4
5
var f = function(name) 
{
   document.write("Hi, " + name + "!");
};
f("Sabine");

Function Expressions are created when the execution flow reaches them.
As a consequence, Function Expressions can be used only after they are defined as seen in the following example:

1
2
3
4
5
6
7
8
9
10
11
  var sayHi;
  var val=4;
  // sayHi() <-- can't call here, there is no sayHi yet
 
  if (val==2) {
    sayHi = function() {  document.write(1);  }
  } else {
    sayHi = function() {  document.write(2); }
  }
 
  sayHi();

In JavaScript – a function is ALSO a value. We could even output it:- what is output? The function definition …

1
2
3
4
5
6
7
// using a function declaration
function f() { document.write (1); }
document.write(f);
 
// using a function expression:
var myFunc = function (name) { document.write (name); }
document.write(myFunc);

Just like any value, a function can be assigned, passed as a parameter for another function and so on. And it doesn’t matter how it was defined, for example:

1
2
3
4
5
6
7
8
9
10
11
 
function sayHi(name) 
{
  document.write("Hi, "+name);
}
 
var hi = sayHi;
 // assign a function to another variable
 
hi("Mark");
// call the function

The function in the above example is assigned by reference. That is, a function is kept somewhere in memory and sayHi is a reference to it. When we assign it to hi, both variables start to reference the same function.

Also, one function can accept another function as an argument:

1
2
3
4
5
6
7
  function runWithOne(f) 
  {  // runs given function with argument 1
    f(1);
  }
 
runWithOne(function(a){ document.write(a) });
// the parameter to runWithOne is an anonymous function definition

Logically, a function is an action. So, passing a function around is transferring an action which can be initiated from another part of the program. This feature is widely used in JavaScript.

Final words on functions:
It is possible to create and run a function created with Function Expression syntax at once, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var myFunction = function() 
{
 
  var a=2;
  var b =3;
  return a+b;
 // local variables 
}();
document.write(myFunction+"<br>");
 
// or
var myFunctionTwo = function(c,d) 
{
 
  var a=2;
  var b =3;
  return a+b+c+d;
 // local variables 
}(4,6);
 
document.write(myFunctionTwo);

Note:: Function Declarations CANNOT be called in this way!

Loops

Loops are a way of repeating the same block of code over and over. They’re incredibly useful. Two of the most common loops are called while loops and for loops.

THE FOR LOOP:
consists of 3 parts which are separated by semi colons:

  • Initialization: A variable is declared and initialized for use within the body of the loop. This variable is most often used inside the loop as a counter.
  • Boolean Test: This is exactly the same as the boolean tests found in conditional statements. It can be any expression that evaluates to true or false.
  • Iteration Expression: The last part is an instruction that you want to happen with each loop cycle.

A for loop construct thus looks like this:

1
2
3
4
5
for(var i =0; i < 10; i= i+1) 
{
// THE BODY OF THE LOOP
// process everything in here while the variable counter is less than 10.
}

Lets implement a basic example using a for loop – we will make a loop that repeats 10 times and for every iteration, we will print out the value of the counter “i”:

1
2
3
for (var i = 0; i < 10; i++) {
    alert(i);
}

Note: here we are using the inbuilt alert box widget – which when called will produce a little popup window with a message in it in the browser.
THE WHILE LOOP:
This construct is similar to a for loop – and can do exactly the same thing – but has a slightly different syntax: A while loop repeats a block of code while a condition is true. Like an if statement, the condition is found in parentheses:

while(expression is TRUE)
{
// THE BODY OF THE LOOP
// process everything in here while the the boolean expression is true
}

So, if we implement the same example using a while loop – it would look like this:: Question – Why do you think we need to increment the counter variable within the body of the loop?

1
2
3
4
5
6
7
8
9
// using a while loop
document.write("<br \>");
document.write("The Same example using a while loop ");
var i =0;
while(i < 10)
{
  alert(i);
   i=i+1;
}

Arrays

So far we have created variables that consisted of one distinct value. We were able to reassign the variable to hold a new value – but the old value would be consequently overwritten. So- what if we want a variable to hold more than one value? – We use arrays…

Arrays are lists of any kind of data, including other arrays. Each item in the array has an index,a number which can be used to retrieve an element from the array. The indices start at 0 ; that is, the first element in the array has the index 0, and subsequent elements have incrementally increasing indices, so the last element in the array has an index one less than the length of the array.

In JavaScript, you create an array using the array-literal syntax:

1
2
var emptyArray = [];
var shoppingList = ['Milk', 'Bread', 'Beans'];

You retrieve a specific element from an array using square bracket syntax:

1
2
document.write("<br \>");
document.write(shoppingList[0]);

It’s also possible to set the value at a particular index, again using the square bracket syntax:
Lets change the 2nd element in the array to “Cookies” and then write out everything in our array (called shoppingList)

1
2
3
4
5
shoppingList[1] = 'Cookies';
// shoppingList is now ['Milk', 'Cookies', 'Beans']
document.write("<br \>");
document.write(shoppingList);
document.write("<br \>");

You can find the number of elements in the array using its length property:

1
2
document.write(shoppingList.length);
document.write("<br \>");

To add and remove elements from the end of the array, we can use the inbuilt push and pop functions respectively:

1
2
3
4
5
6
7
8
shoppingList.push('A new car');
// shoppingList is now ['Milk', 'Cookies', 'Beans', 'A new car']
document.write("<br \>");
document.write("pushed:: "+shoppingList);
shoppingList.pop();
// shoppingList is back to ['Milk', 'Cookies', 'Beans']
document.write("<br \>");
document.write("popped:: "+shoppingList);

Finally – what if we want to iterate (access each element in the list in order of the index) and perhaps change each element somehow?

Solution: We will use a for loop – remember: this is a construct which allows us to repeat an instruction for a finite number of times. To setup a for loop to iterate through the elements in an array – we do the following:

1
2
3
4
for(var index =0; index< shoppingList.length; index++)
{
  // access each element in the shoppingList array.
}

We have set up our loop to start at 0, it will end when the index is equal to the length of the list and with each iteration, the index will increment by 1. Now within the curly braces let us just print out each element in the array along with the index for each iteration:

1
2
3
// access each element in the shoppingList array.
	document.write("<br \>");
	document.write(shoppingList[index]+" index: "+ index);

Here’s an example that contains quite a few of the concepts that we have just covered:
We create, push, pop and iterate over an array, passing each name to a function called helloFrom.

helloFrom will return a string with a greeting: “Hello from ” and then the person’s name. After the pushing and popping, the final list of people is: “Tom”, “Yoda”, “Ron” and “Bob”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function helloFrom(personName) 
{
    return "Hello from " + personName;
}
var people = ['Tom', 'Yoda', 'Ron'];
 
people.push('Bob');
people.push('Dr Evil');
// remove Dr.Evil
people.pop();
 
for (var i=0; i < people.length; i++) {
    var greeting = helloFrom(people[i]);
    alert(greeting);
}

Having gone through the very basic concepts of programming in JavaScript we are now ready to use java script with HTML:

The DOM

There is an inherent structure with regards to any HTML elements (p,div, h1 …) present in an HTML page. The DOCUMENT OBJECT MODEL (DOM) is the model which defines the rules by which an HTML document can be broken down: each element in an HTML document is broken down into discrete objects, each with its own properties and methods.- Importantly, due to the existence of the DOM – we can use JavaScript to manipulate and alter the HTML elements in an HTML page.

Trees & Branches
HTML has a structure where the HTML elements form a structure of parents’ nodes with children, like the branches of a tree. There is one root element:html with branches like head and body, each with their own branches. For this reason, the DOM is also called the DOM tree. Given the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!doctype html>
<html>
<head>
   <title>the title</title>
</head>
<body>
   <div>
      <p>This is a paragraph.</p>
      <p>This is second paragraph.</p>
      <p>This is third paragraph.</p>
   </div>
</body>
</html>

The important points about the above example tree structure is the following:

  • The <html> is the ancestor(pareent) of all the other elements; and therefore: all the other elements are descendants (children) of <html>.
  • The <head> and <body> elements are not only descendants, but immediate children of <html>, as well.
  • Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent.
  • The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements.

We can modify the DOM, by picking an element and changing something about it (i.e. the color of the element) – this altering process is often done using JavaScript. To access the DOM from JavaScript, the document object is used. It is provided by the browser and allows code on the page to interact with the content.

Getting an Element
So, how do we access an existing HTML element in the HTML page? There are a number of ways of doing it, and browsers support different ones:
1/ Accessing the element by “ID”:
document.getElementById is a method for getting hold of an element by its ID.
Lets do a small example: First let us create the following HTML page:

1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<html>
<head>
<title>testing JavaScript and the DOM</title>
<style>.box {width:100px;height:100px;background:red;}</style>
</head>
<body>
<div class ="box">
</div>
</body>
</html>

What we currently should see in the browser is a red rectangle. Now if I want to access the “box” element by its “ID” – the first thing I need to do is add an id property to the div tag:

1
<div class ="box" id ="myRedBox">

Next: if within the script tags in the html we declare and assign the following variable after the html element within the body:

1
2
3
4
<script>
var boxOne = document.getElementById('myRedBox');
alert(boxOne);
</script>

What we now see when we run the page in the browser is the name of the corresponding HTML div element.
Question – what would happen if we put the script BEFORE the html element that we are trying to access? Try it! – Well, we see that the alert box will return null . Why? Because we are running the script before the page is fully loaded…

Therefore – it is always good practice to not worry abut WHERE you place the script – rather lets modify our script to tell it to only run ONCE the document has fully loaded.

1
2
3
4
5
6
7
<script>
window.onload =function()
{
	var boxOne = document.getElementById('myRedBox');
	alert(boxOne);
};
</script>

And now the script will also work if we place the script all the way in the head tag …From this moment onwards we will always follow this construct.

Notice that the getElementById() is a method of the document object. Many of the methods used to access the page are found on the document object.

2/ We can also access HTML elements by “Tag Name”:

The method document.getElementsByTagName works in much the same way as getElementById(), except that it takes a tag name (a, ul, li, etc) instead of an ID and returns all elements in the page with the required tag. Note: Even if there is only one element with that tag name, Javascript will return a list (array) with one element in it .
In the following example we add another div tag and then retrieve both together …

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html>
<head>
<title>testing JavaScript and the DOM</title>
<style>.box {width:100px;height:100px;background:red;}</style>
<script>
window.onload =function()
{
  var bothBoxes = document.getElementsByTagName('div');
  alert(bothBoxes);
};
</script>
 
</head>
<body>
<div class ="box" id="myRedBox"></div>
<div class ="box" id="myRedBox2"></div>
</body>
</html>

3/ Finally, another common method for accessing HTML elements is by “Class Name”:

The method document.getElementsByClassName() returns the same kind of list as getElementsByTagName(), except that you pass a class name to be matched, not a tag name. Recall that we have also used the class property of an HTML element in order to assign a particular style to that element… Given our previous example – let us now access the boxes by their class name:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!doctype html>
<html>
<head>
<title>testing JavaScript and the DOM</title>
<style>.box {width:100px;height:100px;background:red;}</style>
<script>
window.onload =function()
{
   var bothBoxesC = document.getElementsByClassName('box');
   alert(bothBoxesC);
};
</script>
</head>
<body>
<div class ="box" id="myRedBox"></div>
<div class ="box" id="myRedBox2"></div>
</body>
</html>

Changing HTML content (.innerHTML)
The innerHTML property is a pointer to the HTML content within a particular element, allowing you to easily access or change the content. The example below is similar to the previous one, but it prints the HTML within the elements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!doctype html>
<html>
<head>
<title>testing JavaScript and the DOM</title>
<style>.box {margin:1%;width:50px;height:50px;background:red; color:white; font-size:1em;text-align:center;}</style>
<script>
window.onload =function()
{
   var bothBoxesC = document.getElementsByClassName('box');
   //how many boxes are there?
   console.log(bothBoxesC.length);
 
   // as what was returned is an array  - we iterate through it and retrieve the html
   for(var i =0; i< bothBoxesC.length; i++)
   {
      console.log(bothBoxesC[i].innerHTML);
   }
};
</script>
</head>
<body>
<div class ="box" id="myRedBox">boxA</div>
<div class ="box" id="myRedBox2"><p>boxB</p></div>
</body>
</html>

Note: how the .innerHTML property outputs also all the HTML markup within the specified element.

Therefore, if we just wanted the text content pertaining to a particular html element we could use the .textContent method (as it does not parse HTML):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!doctype html>
<html>
<head>
<title>testing JavaScript and the DOM</title>
<style>.box {width:100px;height:100px;background:red;}</style>
<script>
window.onload =function()
{
   var bothBoxesC = document.getElementsByClassName('box');
   //how many boxes are there?
   console.log(bothBoxesC.length);
 
   // as what was returned is an array  - we iterate through it and retrieve the text
   for(var i =0; i< bothBoxesC.length; i++)
   {
      console.log(bothBoxesC[i].textContent);
   }
};
</script>
</head>
<body>
 
<div class ="box" id="myRedBox">BoxA</div>
<div class ="box" id="myRedBox2"><p>BoxB</p></div>
</body>
</html>

In summary: textContent outputs text/plain while .innerHTML outputs text/html. Output of type text/plain is not parsed by the browser and results in the full content displaying. Output of the type text/html tells the browser to parse it before displaying it.
This can be demonstrated furthur when we want to change the content within the element, by setting the innerHTML or textContent property equal to some new value:

1
2
3
4
 //change the HTML of boxA..
   bothBoxesC[0].innerHTML ="<p>boxy box B</p>";
// also works but is different - why?
//bothBoxesC[1].textContent="<p>boxy box BQ</p>";

Changing an Attribute:
You can change an element’s attribute using a similar form, but replacing “innerHTML” with your desired attribute tag. The following example changes the src attribute of an image:
bird_redS blue-bird.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html>
<head>
<title>testing JavaScript and the DOM</title>
<style>.box {margin:1%;width:50px;height:50px;background:red; color:white; font-size:1em;text-align:center;}</style>
<script>
window.onload =function()
{
   var boxImage = document.getElementById('A');
   boxImage.src = "images/blue-bird.jpg";
 
};
</script>
</head>
<body>
<div class ="box" id="myRedBox"><img id ="A" src ="images/bird_redS.png" width ="50px" height ="50px"></div>
<div class ="box" id="myRedBox2">boxB</div>
</body>
</html>

You can also change the style attribute of an element. In this case, you use the style attribute tag, which is followed by another “.” and the particular style property to change.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!doctype html>
<html>
<head>
<title>testing JavaScript and the DOM</title>
<style>.box {margin:1%;width:50px;height:50px;background:red; color:white; font-size:1em;text-align:center;}
   #first{color:black; font-size:1em;}
   </style>
<script>
window.onload =function()
{
   var elt = document.getElementById("first");
   elt.style.color = "red";
   elt.style.background = "pink";
   elt.style.padding = "18px";
 
};
</script>
</head>
<body>
  <p id ="first"> This is a paragraph ... </p> 
<div class ="box" id="myRedBox"><img id ="A" src ="images/bird_redS.png" width ="50px" height ="50px"></div>
<div class ="box" id="myRedBox2">boxB</div>
</body>
</html>

setTimeout & setInterval
Sometimes it’s useful to be able to schedule a function call for some time in the future. To handle this there are two functions: setTimeout() and setInterval() . Both functions take two arguments, the function to be executed, and a delay amount (in milliseconds). setTimeout schedules a one-time function call, while setInterval schedules a recurring function call.
Note that when you pass in the function to be called no quotes or parentheses are needed, you are passing the variable pointing to the function. For example:

1
2
3
4
5
6
7
8
9
10
11
   function doSomething() {
     console.log("hi");
   }
 
   setTimeout(doSomething, 2000); // call doSomething in 2 seconds
 
   function doSomethingElse() {
     console.log("hi Reoccurring");
   }
 
   setInterval(doSomethingElse, 1000); // call doSomethingElse every second

We can then use these functions to change the style, position, content, etc … for any element on the page. Lets look in detail at the following example::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<html>
<head>
  <title>Set Interval Ex</title>
<style>
body{
  background:black;
  margin:0;
  padding:0;
}
#rowOfBoxes {
    height: 116px;
    width: 812px;
    padding-right: 10px;
    padding-top: 50px;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}
 
.box {
    width: 100px;
    height: 100px;
    margin-left: 10px;
    margin-top: 10px;
    float:left;
 
}
 
#c {
    background-color: #3e181b;
    border: 3px solid #db1d2d;
}
 
#d {
    background-color: #422018;
    border: 3px solid #f0421c;
}
 
#e {
    background-color: #45391b;
    border: 3px solid #fec02d;
}
 
#f {
    background-color: #193c29;
    border: 3px solid #20d071;
}
 
#g {
    background-color: #18323e;
    border: 3px solid #1a9ddb;
  }
  #a {
    background-color: #331f35;
    border: 3px solid #a13fad;
 
}
 
#b {
    background-color: #43293d;
    border: 3px solid #f26fd4;
}
 
</style>
<script>
window.onload = function()
{
  //set all boxes to have an opacity of 1.0
  var boxes = document.getElementsByClassName("box");
  for(var i=0; i<boxes.length; i++)
  {
    boxes[i].style.opacity =1.0;
  }
 
/* change opacity callback */
  function changeOpacity(theE, theIntervalVariable)
  {
 
    var elementA = document.getElementById(theE);
    console.log("opacity:: "+elementA.style.opacity);
    if(elementA.style.opacity>0.05)
      elementA.style.opacity-=.05;
    else {
    //  console.log("done");
    clearInterval(theIntervalVariable);
    }
  }
  /* lets make 2 different interval variables for each box ...*/
  var intervalA = setInterval(function(){
 
    changeOpacity("c", intervalA)
 
  },500);
 
  var intervalB = setInterval(function(){
    changeOpacity("d", intervalB)
  },1000);
 
}
</script>
 
</head>
<body>
 
 
  <div id="rowOfBoxes">
	<div id="c" class="box"></div>
	<div id="d" class="box"></div>
	<div id="e" class="box"></div>
	<div id="f" class="box"></div>
	<div id="g" class="box"></div>
	<div id = "a" class="box"></div>
	<div id="b" class="box"></div>
</div>
 
</body>
</html>

SO – we have a row of boxes – and 2 of the boxes currently change opacity over time thanks to the setInterval function …
Note::

  • We first set the opacity style property for each box – in order to access it later
  • We have a function called changeOpacity() that takes 2 parameters – the first one being for which element we are trying to access and the second for which setInterval function is accessing this callback. Having these parameters allows us to generalize: we only need one changeOpacity() function and NOT one for every element…
  • The reason behind accessing the setInterval function by name allows us to STOP the function from executing given a particular condition. We STOP the setInterval function from occurring using the clearInterval() function.

We need not only change the opacity of a box… lets try animate 2 boxes … (e,f):

  • We need to change the css of the class box to have a position property (i.e. relative)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    .box {
        width: 100px;
        height: 100px;
        margin-left: 10px;
        margin-top: 10px;
        float:left;
        /* new to allow for an element to move */
        position:relative;
     
    }
  • We need to initially give each box a left and top style property (like we did for opacity)
    1
    2
    3
    4
    5
    6
    7
    8
    
    for(var i=0; i<boxes.length; i++)
      {
        boxes[i].style.opacity =1.0;
        // also set a top property - using the inbuilt offsetTop property set when page loads
        boxes[i].style.top =boxes[i].offsetTop+"px";
       // also set a left property - using the inbuilt offsetLeft property set when page loads
       boxes[i].style.left =0+"px";
      }
  • We define our move functions()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    
    //function to move on yAxis
      function moveBoxY(theE, theIntervalVariable)
      {
        var elementA = document.getElementById(theE);
        var theOffsetAsAnInt = parseInt(elementA.style.top.substring(0,elementA.style.top.length-2));
     
        if(theOffsetAsAnInt <120)
        elementA.style.top = theOffsetAsAnInt+1+"px";
     
        else {
        //  console.log("done");
        clearInterval(theIntervalVariable);
        }
      }
    //function to move on xAxis
      function moveBoxX(theE, theIntervalVariable)
      {
        var elementA = document.getElementById(theE);
        var theOffsetAsAnInt = parseInt(elementA.style.left.substring(0,elementA.style.left.length-2));
     
        if(theOffsetAsAnInt <80)
        elementA.style.left = theOffsetAsAnInt+1+"px";
        else {
        //  console.log("done");
        clearInterval(theIntervalVariable);
        }
    }
  • Note: We need to do some extra work to get the correct position and update it – this is because javascript returns a string and we need to cast the value as a number …
  • We define and call our setInterval functions:
    1
    2
    3
    4
    5
    6
    7
    8
    
     
    var intervalC= setInterval(function(){
        moveBoxY("e", intervalC);
      },100);
     
      var intervalD= setInterval(function(){
        moveBoxX("f", intervalC);
      },100);

And we are done!

Events and CallBacks

Up until now we have been executing the document.write() function from within the <script> tags or using the “alert()” function to output the result from executing JavaScript statements.
However, a JavaScript function defined within the <script> tags can also be called directly when a specific event occurs.
What is an event?::
An event is some “action” (like when a user “clicks” on a button), which when occurs will cause some change to take place (i.e: when the user clicks on a menu item in an HTML page, the requested page will be loaded in the browser…).
Therefore, in the browser most code is “event-driven” and writing interactive applications in JavaScript is often about waiting for and reacting to events, to alter the behavior of the browser in some way. Events occur when the page loads, when user interacts (clicks, hovers, changes) and a myriad of other times, and can be triggered manually too… In fact – the setInterval() and setTimeout() functions are event driven – in the sense that they specify that a particular action should occur, triggered by a time event.

In order to react to an event one needs to write code which on one hand “listens for the event to occur”, and when it occurs one needs to supply a function which will be called by the browser when the event occurs. This function is also known as a callback.
Here’s a group of the commands needed to listen for an event:-

  1. the callback function
  2. an element
  3. the call to listen for an event
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<!doctype html>
<html>
<head>
  <title>Mouse Events</title>
<style>
body{
  background:black;
  margin:0;
  padding:0;
}
#rowOfBoxes {
    height: 116px;
    width: 812px;
    padding-right: 10px;
    padding-top: 50px;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}
 
.box {
    width: 100px;
    height: 100px;
    margin-left: 10px;
    margin-top: 10px;
    float:left;
    /* new to allow for an element to move */
    position:relative;
 
}
 
#c {
    background-color: #3e181b;
    border: 3px solid #db1d2d;
}
 
#d {
    background-color: #422018;
    border: 3px solid #f0421c;
}
 
#e {
    background-color: #45391b;
    border: 3px solid #fec02d;
}
 
#f {
    background-color: #193c29;
    border: 3px solid #20d071;
}
 
#g {
    background-color: #18323e;
    border: 3px solid #1a9ddb;
  }
  #a {
    background-color: #331f35;
    border: 3px solid #a13fad;
 
}
 
#b {
    background-color: #43293d;
    border: 3px solid #f26fd4;
}
 
</style>
<script>
window.onload = function()
{
 
 
  var handleClick = function (event)
  {
          // do something!
          alert("box c was clicked");
  };
  var cBox = document.getElementById('c');
  cBox.addEventListener('click', handleClick);
}
</script>
 
</head>
<body>
 
 
  <div id="rowOfBoxes">
	<div id="c" class="box"></div>
	<div id="d" class="box"></div>
	<div id="e" class="box"></div>
	<div id="f" class="box"></div>
	<div id="g" class="box"></div>
	<div id = "a" class="box"></div>
	<div id="b" class="box"></div>
</div>
 
</body>
</html>

If you replace the the above in your html page – now when you run your page in the browser – and you click on the “correct” box – then an alert message will be displayed::: But how does this pattern work?

  • addEventListener is a method found on all DOM elements. Here it’s being called on an element saved in the “cBox” variable. The first argument is a string – the name of the event to listen for. Here’s it’s click – that’s a click of the mouse or a tap of the finger. The second is the callback function – here it’s called handleClick.
  • The handleClick function is defined above – it takes “an event”(the click of the mouse) as a parameter – and is defined to execute the code within the curly braces in this case an alert message.
  • So putting this altogether: the element whose id is “c” has an event listener attached to it – and therefore when it is “clicked”, the function called “handleClick” will be executed.

Using this
You could also modify the element when the click event happens. Within an event handler function, the variable “this” is automatically assigned to the element that received the event:

1
2
3
4
5
6
7
 var handleClick = function (event)
     {
        this.style.background = "#800000";
     };
     var cBox = document.getElementById('c');
     cBox.addEventListener('click', handleClick);
 }

Note::: The onclick is an example of an HTML DOM event. HTML DOM events allow for JavaScript to register different event handlers on elements in an HTML document (i.e a div element). Events are normally used in combination with functions, and the function will not be executed before the event occurs. There are a lot of different input events detected by the browser, you can see a full list on the Mozilla event reference. Some useful ones include:

  • mouse:: – mousedown, mousemove, mouseup, mouseover, mouseout, mousewheel
  • touch:: – touchstart, touchmove, touchend, touchenter, touchleave
  • keyboard:: – keydown, keypress, keyup

The next example is a little bit more complex: so bear with me – bascially we will implment the functionality for our boxes to move with the mouse:

  • We need to capture when the mouse is moving
  • We need to capture when the mouse has clicked on a particular box (mouse down)
  • If the mouse is moving and has clicked on a box – we need to update the position of our box to that of the mouse.
  • Finally: we want to capture when the mouse is released – and therefore the box will stop moving …

Copy and paste the following and run it in your browser – we will then go over each part:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<html>
<head>
  <title>Mouse Events</title>
<style>
body{
  background:black;
  margin:0;
  padding:0;
}
#rowOfBoxes {
    height: 116px;
    width: 812px;
    padding-right: 10px;
    padding-top: 50px;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}
 
.box {
    width: 100px;
    height: 100px;
    position:absolute;
 
}
 
#c {
    background-color: #3e181b;
    border: 3px solid #db1d2d;
    left:10px;
}
 
 
</style>
<script>
window.onload = function()
{
 var currentX = 0, currentY = 0, previousX = 0, previousY = 0;
 var onBox = false;
var handleDown = function (event)
{
  console.log("down");
  onBox =true;
};
 
var handleUp = function (event)
{
  console.log("up");
    onBox =false;
 
};
 
var handleMove = function (event)
{
  if(onBox ==true)
  {
    console.log("here");
  var theElement = document.getElementById("c");
 
    currentX = previousX - event.clientX;
    currentY = previousY - event.clientY;
    previousX = event.clientX;
    previousY = event.clientY;
 
    // set the element's new position:
   theElement.style.top = (theElement.offsetTop - currentY) + "px";
   theElement.style.left = (theElement.offsetLeft - currentX)+"px";
 }
 
};
 
var theElement = document.getElementById("c");
theElement.addEventListener('mousedown', handleDown);
window.addEventListener('mouseup', handleUp);
window.addEventListener('mousemove', handleMove);
 
 }
 
</script>
</head>
<body>
	<div id="c" class="box"></div>
</body>
</html>

Window events
Events can be element specific: that is, you attach them to a single element, and they are fired only when that element receives the event. in There are also some events that happen on a global window level – Note: in the last example we just used window events to detect if the mouse was moving or released. Other examples are resize and load. In this case, you say window. instead of element.. We have already usedthe “window.onload” event…. You can refer to w3schools for a description of the Window Object and the associated properties.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<html>
<head>
  <title>Mouse Events</title>
<style>
body{
  background:black;
  margin:0;
  padding:0;
}
 
.box {
    width: 100px;
    height: 100px;
    float:left;
    margin-left:10px;
    margin-top: 50px;
 
}
 
#c {
    background-color: #3e181b;
    border: 3px solid #db1d2d;
 
}
 
#d {
    background-color: #422018;
    border: 3px solid #f0421c;
    width: 200px;
    color:white;
    font-size:10pt;
}
 
</style>
<script>
 
 
 
window.onload =function()
{
 
     function handleResize() {
       // in this case, "this" doesn't point to an element
       // "this" refers to the window since that's where
       // the event occurred, so we have to grab it to use it
       var elt = document.getElementById("d");
       elt.innerHTML += "\nI've been resized!";
       var width =  window.innerWidth;
      //Returns the inner width of a window's content area
      var height=  window.innerHeight;
     //Returns the inner height of a window's content area
     console.log("view port width: "+width);
     console.log( "view port height" +height);
 }
 
     window.addEventListener("resize", handleResize);
 
 }
 
</script>
</head>
<body>
	<div id="c" class="box"></div>
  <div id="d" class="box"></div>
</body>
</html>

Adding elements to the DOM

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element. The following example demonstrates the appendChild() method which adds the element at the end of the parent – as well as the insertBefore() method which adds the new element before an existing element:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<html>
<head>
  <title>Append EX</title>
<style>
body{
  background:black;
  margin:0;
  padding:0;
}
#rowOfBoxes {
    height: 116px;
    width: 812px;
    padding-right: 10px;
    padding-top: 50px;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}
 
.box {
    width: 100px;
    height: 100px;
    margin-left: 10px;
    margin-top: 10px;
    /*float:left;*/
    /* new to allow for an element to move */
    display:inline-block;
    position:relative;
 
}
 
#c {
    background-color: #3e181b;
    border: 3px solid #db1d2d;
}
 
#c2 {
  background-color: #45391b;
  border: 3px solid #fec02d;
}
 
#c3 {
  background-color: #3e181b;
  border: 3px solid #db1d2d;
}
 
#d {
    background-color: #422018;
    border: 3px solid #f0421c;
}
 
#e {
    background-color: #45391b;
    border: 3px solid #fec02d;
}
 
#f {
    background-color: #193c29;
    border: 3px solid #20d071;
}
 
#g {
    background-color: #18323e;
    border: 3px solid #1a9ddb;
  }
  #a {
    background-color: #331f35;
    border: 3px solid #a13fad;
 
}
 
#b {
    background-color: #43293d;
    border: 3px solid #f26fd4;
}
 
</style>
<script>
window.onload = function()
 
{
//1: add new element to the body
  var para = document.createElement("p");
  var node = document.createTextNode("This is a new paragraph appended to the body.");
  para.style.color = "white";
  para.style.margin = "10px";
  para.appendChild(node);
  document.body.appendChild(para);
 
//2 access parent element and add to that container
    var parent = document.getElementById("rowOfBoxes");
    var newBox = document.createElement("div");
    newBox.className = "box";
    newBox.id = "c2";
    parent.appendChild(newBox);
 
 
//3 insert b4
 var b1 = document.getElementById("g");
  var b2 = document.createElement("div");
  b1.className = "box";
  b1.id = "c3";
  parent.insertBefore(b2,b1);
 
 
};
</script>
 
</head>
<body>
 
 
  <div id="rowOfBoxes">
	<div id="c" class="box"></div>
	<div id="d" class="box"></div>
	<div id="e" class="box"></div>
	<div id="f" class="box"></div>
	<div id="g" class="box"></div>
	<div id = "a" class="box"></div>
	<div id="b" class="box"></div>
</div>
 
</body>
</html>

Removing elements from the DOM
Finally – you can also remove existing elements from the DOM using the removeChild():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<html>
<head>
  <title>Remove EX</title>
<style>
body{
  background:black;
  margin:0;
  padding:0;
}
#rowOfBoxes {
    height: 116px;
    width: 812px;
    padding-right: 10px;
    padding-top: 50px;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}
 
.box {
    width: 100px;
    height: 100px;
    margin-left: 10px;
    margin-top: 10px;
    /*float:left;*/
    /* new to allow for an element to move */
    display:inline-block;
    position:relative;
 
}
 
#c {
    background-color: #3e181b;
    border: 3px solid #db1d2d;
}
 
#c2 {
  background-color: #45391b;
  border: 3px solid #fec02d;
}
 
#c3 {
  background-color: #3e181b;
  border: 3px solid #db1d2d;
}
 
#d {
    background-color: #422018;
    border: 3px solid #f0421c;
}
 
#e {
    background-color: #45391b;
    border: 3px solid #fec02d;
}
 
#f {
    background-color: #193c29;
    border: 3px solid #20d071;
}
 
#g {
    background-color: #18323e;
    border: 3px solid #1a9ddb;
  }
  #a {
    background-color: #331f35;
    border: 3px solid #a13fad;
 
}
 
#b {
    background-color: #43293d;
    border: 3px solid #f26fd4;
}
 
</style>
<script>
window.onload = function()
 
{
 
   	var clickRemove = function(event)
   	{
      	var parent = document.getElementById("rowOfBoxes");
 
      		var child = document.getElementById("f");
      		if(child!=null)
      		{
      			parent.removeChild(child);
      		}
      		else
      		{
      		console.log("element already removed!");
      		}
      }
 
      var elt = document.getElementById("c");
      elt.addEventListener("click",clickRemove);
};
</script>
 
</head>
<body>
 
 
  <div id="rowOfBoxes">
	<div id="c" class="box"></div>
	<div id="d" class="box"></div>
	<div id="e" class="box"></div>
	<div id="f" class="box"></div>
	<div id="g" class="box"></div>
	<div id = "a" class="box"></div>
	<div id="b" class="box"></div>
</div>
 
</body>
</html>

This concludes the part of the tutorial on basic Java Script. We will continue by looking at a very popular JavaScript library called JQuery which makes coding in JavaScript more fluid and more accessible. Note that when using the JQuery library, there is nothing stopping you from combining the different functions with your own custom JavaScript ones.

Brief Intro to JQuery
JQuery is a popular, fast and concise JavaScript Library created by John Resig in 2006 with a nice motto: Write less, do more. It simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
Important core features supported by jQuery:

  • DOM manipulation: The JQuery library makes it easy to select DOM elements, traverse them and modify their content by using the cross-browser open source selector engine called Sizzle.
  • Event handling: The JQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers.
  • AJAX Support: The JQuery helps you a lot to develop a responsive and feature-rich site using AJAX technology.
  • Animations: The JQuery comes with plenty of built-in animation effects which you can use in your websites.
  • Cross Browser Support: The JQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+.

Lets start with a new html page and first we will include the JQuery Library:
To install JQuery Option 1:
1. Go to the download page to grab the latest version available.
2. Now put downloaded jquery-3.3.1.min.js file in a directory of your website, e.g. JQuery
To include the JQuery library in an HTML page, we will use the script tags and specify the url of the “jquery-3.3.1.min.js”.

1
2
3
4
5
6
7
8
9
<!doctype html>
<html>
<head>
<title>JQuery Example page</title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
</body>
</html>

To use JQuery Library functions:::
As almost everything one does when using JQuery is either reading or manipulating the document object model (DOM), we need to make sure that we start adding events etc… ONLY once the DOM is ready (when the page has completed loading).

To do this, we register a ready event for the document as follows:

1
2
3
4
5
<script>
$(document).ready(function() {
   // do stuff when DOM is ready
 });
</script>

Place the script just before the end of the head tags. Now that we have the JQuery function which executes ONLY when the HTML document is “ready’ – we will now implement the same clicking functionality as we just did previously with native JavaScript, however now we will use JQuery. So first let put back our original html markup with the boxes(within the body tags):

1
2
3
4
5
6
7
8
9
10
11
<body>
  <div id="rowOfBoxes">
	<div id="c" class="box"></div>
	<div id="d" class="box"></div>
	<div id="e" class="box"></div>
	<div id="f" class="box"></div>
	<div id="g" class="box"></div>
	<div id="a" class="box"></div>
	<div id="b" class="box"></div>
</div>
</body>

And lets also put our styles back in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<style>
body{
  background:black;
  margin:0;
  padding:0;
}
#rowOfBoxes {
    height: 116px;
    width: 812px;
    padding-right: 10px;
    padding-top: 50px;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}
 
.box {
    width: 100px;
    height: 100px;
    margin-left: 10px;
    margin-top: 10px;
    float:left;
    /* new to allow for an element to move */
    position:relative;
 
}
 
#c {
    background-color: #3e181b;
    border: 3px solid #db1d2d;
}
 
#d {
    background-color: #422018;
    border: 3px solid #f0421c;
}
 
#e {
    background-color: #45391b;
    border: 3px solid #fec02d;
}
 
#f {
    background-color: #193c29;
    border: 3px solid #20d071;
}
 
#g {
    background-color: #18323e;
    border: 3px solid #1a9ddb;
  }
  #a {
    background-color: #331f35;
    border: 3px solid #a13fad;
 
}
 
#b {
    background-color: #43293d;
    border: 3px solid #f26fd4;
}
 
</style>

OK – now whats next: We need to “select” the relevant div that should be clickable – and we want an “action” to occur once this “div” has been clicked. Let’s say we want the div with id “c” to be clickable – then within the function which executes once the document is “ready” we place the following:

1
2
3
4
5
$("#c").on("click", function(){
 // here we do stuff once the div has been clicked
 console.log("jquery click");
$(this).css("background","#800000");
})

So – what we have done is essentially “registered” an event handler with the div, and specified that the required event to occur is “click” – once we have done this – we also specify a “callback” function whic changes the background color of the appropriate box (like before) Now: when you run the page in your browser – you should have exactly the same results as in the previous example. So – why use the JQuery library? — Because the JQuery library uses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM).
Therefore: A JQuery Selector is a function which makes use of specific expressions to find the matching elements from a DOM based on the given criteria. We will now go through some of the most common JQuery Selector functions:

The $() factory function:
** Important: For all type of selectors available in JQuery, they always start with the dollar sign and include parentheses: $().
The factory function $() makes use of following three building blocks while selecting elements in a given document:

  1. The Tag Name:Represents a tag name available in the DOM. For example $(‘p’) selects all paragraphs in the document.
  2. The Tag ID: Represents a tag available with the given ID in the DOM. For example $(‘#some-id’) selects the single element in the document that has an ID of some-id.
  3. Tag Class: Represents a tag available with the given class in the DOM. For example $(‘.some-class’) selects all elements in the document that have a class of some-class.

Let’s modify the example to demonstrate how easily we can access and change another element when a click event occurs:

1
2
3
4
5
6
7
$("#c").on("click", function(){
 // here we do stuff once the div has been clicked
 console.log("jquery click");
//$(this).css("background","#800000");
$("#d").css("background", "#f0421c");
 
}

This last example demonstrates a few more simple Jquery functions i.e. show() and hide(). It also shows simple array usage and targeting elements with JQuery:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
 
<!doctype html>
<html>
<head>
<title>JQuery Example page</title>
<script src="jquery-3.3.1.min.js"></script>
 
<style>
body{
  background:black;
  margin:0;
  padding:0;
}
#rowOfBoxes {
    height: 116px;
    width: 812px;
    padding-right: 10px;
    padding-top: 50px;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
 
 
}
 
.box {
    width: 100px;
    height: 100px;
    margin-left: 10px;
    margin-top: 10px;
    float:left;
    /* new to allow for an element to move */
    position:relative;
 
}
 
#c {
    background-color: #3e181b;
    border: 3px solid #db1d2d;
}
 
#d {
    background-color: #422018;
    border: 3px solid #f0421c;
}
 
#e {
    background-color: #45391b;
    border: 3px solid #fec02d;
}
 
#f {
    background-color: #193c29;
    border: 3px solid #20d071;
}
 
#g {
    background-color: #18323e;
    border: 3px solid #1a9ddb;
  }
  #a {
    background-color: #331f35;
    border: 3px solid #a13fad;
 
}
 
#b {
    background-color: #43293d;
    border: 3px solid #f26fd4;
}
 
.mainContent{
  clear:both;
  margin-left: 10px;
  width:800px;
  height:200px;
  background-color: #331f35;
  color:white;
  position:relative;
  left:0%;
  top:10px;
  padding-left:5px;
  padding-top:50px;
  text-align: center;
  font-size:16pt;
  font-family:sans-serif;
}
 
</style>
<script>
$(document).ready(function(){
 
  var texts = ["text C","text D","text E","text F","text G","text A","text B"];
$(".mainContent").hide();
 
$(".box").on("mouseover", function(){
 
  $(".mainContent").show();
 
  console.log($(this).attr('id'));
 
if($(this).attr('id')=="c")
{
    $(".pContent").html(texts[0]);
 
}
else if($(this).attr('id')=="d"){
  $(".pContent").html(texts[1]);
}
else if($(this).attr('id')=="e"){
  $(".pContent").html(texts[2]);
}
 
else if($(this).attr('id')=="f"){
  $(".pContent").html(texts[3]);
}
 
else if($(this).attr('id')=="g"){
  $(".pContent").html(texts[4]);
}
 
else if($(this).attr('id')=="a"){
  $(".pContent").html(texts[5]);
}
else if($(this).attr('id')=="b"){
  $(".pContent").html(texts[6]);
}
 
});
 
$(".box").on("mouseout", function(){
 
  $(".mainContent").hide();
 
});
 
});
 
</script>
</head>
<body>
  <div id="rowOfBoxes">
	<div id="c" class="box"></div>
	<div id="d" class="box"></div>
	<div id="e" class="box"></div>
	<div id="f" class="box"></div>
	<div id="g" class="box"></div>
	<div id="a" class="box"></div>
	<div id="b" class="box"></div>
  <div class ="mainContent">
    <h3 class = "pContent"></h3>
  </div>
</div>
 
</body>
</html>

The examples given so far are merely to demonstrate how one can easily manipulate the DOM using JQuery. I recommend that you look further at the available documentation.

JQuery Exercise

Given the following template (html +css):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
 
<!doctype html>
<html>
<head>
<title>JQuery Example page</title>
<script src="jquery-3.3.1.min.js"></script>
 
<style>
body{
  background:black;
  margin:0;
  padding:0;
}
#rowOfBoxes {
    height: 500px;
    width: 500px;
    padding-right: 10px;
    padding-top: 50px;
    position: absolute;
    top: 0; left: 0;
    background: rgba(255,255,255,0.2);
    margin:50px;
 
 
}
 
.box {
    width: 100px;
    height: 100px;
    position:absolute;
    margin-left:2px;
}
 
#c {
    background-color: #3e181b;
    border: 3px solid #db1d2d;
    left:50px;
    top:50px;
}
 
#d {
    background-color: #422018;
    border: 3px solid #f0421c;
    left:160px;
    top:50px;
}
 
#e {
    background-color: #45391b;
    border: 3px solid #fec02d;
    left:50px;
    top:160px;
}
 
#f {
    background-color: #193c29;
    border: 3px solid #20d071;
    left:160px;
    top:160px;
}
.inner{
  width:50px;
  height:50px;
  background:rgba(255,255,255,0.2);
  position:relative;
  left:25%;
  top:25%;
  display:none;
}
</style>
 
</head>
<body>
  <div id="rowOfBoxes">
	<div id="c" class="box"><div class ="inner" id ="innerC"></div></div>
	<div id="d" class="box"><div class ="inner" id ="innerD"></div></div>
	<div id="e" class="box"><div class ="inner" id ="innerE"></div></div>
	<div id="f" class="box"><div class ="inner" id ="innerF"></div></div>
 
</div>
 
</body>
</html>

Using Jquery – please implement the following functionality:

  • When you mouse-enter over one of the boxes, show the child inner box
  • When you mouse-leave over one of the boxes, hide the child inner box

Extracting data from the web using JQuery

In order to extract data from the web (web server where a specific site is hosted), we will utilize a methodology known as AJAX.

AJAX = Asynchronous JavaScript and XML.
AJAX is not a new programming language, but a new-ish way to use existing standards.
AJAX is the art of exchanging data with a server, and updating parts of a web page – without reloading the whole page.

But what is AJAX?

  • Asynchronous: This means that when you send a request, you wait for the response to come back, but are free to do other things while you wait. The response probably won’t come back immediately, so you set up a functionthat will wait for the response to be sent back by the server, and react to it once that happens.
  • JavaScript: is used to make a request to the server. Once the response is returned by the server, you will generally use some more JavaScript to modify the current page’s document object model in some way to show the user that the submission went through successfully.
  • XML: The data that you receive back from the server was first packaged up as a snippet of XML, so that it can be easily processed with JavaScript.**Note: the current trend is to use JSON objects (JavaScript Object Notation). This data can be anything you want, and as long as you want.

If you have previously done a bit of server side scripting then there’s nothing really new about what is happening here. We’re requesting a file (which will often be a server-side script, coded in something like PHP), and receiving a page as the response. This is how the web works already — the only difference is that now we can make these requests from JavaScript….

Steps of an AJAX Operation:

  1. A client event occurs
  2. An XMLHttpRequest object is created
  3. The XMLHttpRequest object is configured
  4. The XMLHttpRequest object makes an asynchronous request to the Webserver.
  5. The Webserver returns the result containing the XML document (or JSON object).
  6. The XMLHttpRequest object calls the callback() function and processes the result.
  7. The HTML DOM is updated.

We could now decide to use native javascript to send /receive data asynchronously – but it is pretty cumbersome and you will be happy to know that JQuery has a whole library of easy to use methods for sending and receiving data in multiple ways:

Loading simple HTML data via the JQuery load() method:


1
[selector].load( URL, [data], [callback] );

The parameters are explained below:

  • URL: The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database.
  • data: This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used.
  • callback: A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text recieved from the server and second parameter is the status code.

A simple example using the Jquery “load()”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<html>
<head>
<title>the title</title>
    <script src="jquery-3.3.1.min.js"></script>
   <script>
   $(document).ready(function() {
      $("#loadTheHTMLFromServer").click(function(event){
          $('#resultDiv').load('result.html');
      });
   });
   </script>
</head>
<body>
   <p>Click on the button to load result.html file:</p>
   <div id="resultDiv" style="background-color:blue; color:white">
          RESULT
   </div>
   <input type="button" id="loadTheHTMLFromServer" value="Load Data" />
</body>
</html>

In this example the JQuery load() initiates an Ajax request to the specified URL: the result.html file. Upon success (of loading the file), all the content from this page will be populated into the specified div tag.
The result.html file contains:

1
<h1> This is the text from result.html </h1>

So we need to create this result page – save it in the same directory as your load page – then test. Note: we are currently only working locally. However, the same concept applies if you were running your example on a web server – i.e. hybrid… so try it.

Getting JSON (JavaScript Object Notation) data:

There are many instances where the data returned from the server is a JSON object. JQuery once again has a special method for returning JSON objects:
The getJSON() method will parse the returned JSON object, and makes it available to the callback function:

1
[selector].getJSON( URL, [data], [callback] );

The following list explains the parameters:

  • URL: The URL of the server-side resource contacted via the GET method.
  • data: An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string.
  • callback: A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second.

A simple example for retrieving and displaying a JSON object within an HTML page:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!doctype html>
<html>
<head>
<title>LOAD JSON EX</title>
  <script src="jquery-3.3.1.min.js"></script>
   <script>
   $(document).ready(function() {
 
      $("#run").click(function(event){
 
          $.getJSON('result.json', function(result) {
          //returns an array
             console.log(result.length);
             for(var i=0; i< result.length; i++)
             {
              $('#resultSet').append('<div class ="entry "id ="resultEntry'+i+'">');
             	$('#resultEntry'+i).append('<p> Name: ' + result[i].name + '</p>');
            	$('#resultEntry'+i).append('<p>Age : ' + result[i].age+ '</p>');
             	$('#resultEntry'+i).append('<p>Gender: ' + result[i].gender+ '</p>');
             	$('#resultEntry'+i).append('<p> nationality: ' + result[i].nationality+ '</p>');
              $('#resultEntry'+i).append('</div>');
             }
          });
      });
   });
   </script>
   <style>
   .entry{
     margin-top:10px;
     margin-bottom:10px;
     margin-left:10px;
     margin-right:10px;
     background:rgba(246,246,246,0.2);
 
   }
  </style>
</head>
<body>
   <p>Click on the button to load result file:</p>
   <div id="resultSet" style="background-color:orange;color:black; padding:10px;">
          <h4>RESULT SET</h4>
   </div>
   <input type="button" id="run" value="Load Data" />
</body>
</html>

This example assumes we have a result.json file on the server in the following format:

1
2
3
4
5
6
7
8
9
10
11
12
[{
"name": "Maria Johnson",
"age" : "22",
"gender": "female",
"nationality":"british"
},
{
"name": "Sandra Helson",
"age" : "45",
"gender": "female",
"nationality":"brazilian"
}]

Note: this example may not work if you run the page in your browser (locally) – you will need to uplaod the html+jquery+json to a web server – to view the page working you can visit: my hybrid web page.

Now that we have a very basic understanding of accessing data from the server using AJAX – we can finally come to the point in this tutorial for accessing data from resources such as Twitter, Flickr, Bing etc…

Accessing and displaying Results from Flickr::

The following example will allow you to quickly retrieve results from flickr:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Accessing FLICKR data using the jQuery.getJSON() </title>
<style>
img {
height: 100px;
float: left;
display:inline-block;
margin-left:10px;
margin-top:10px;
}
</style>
 <script src="jquery-3.3.1.min.js"></script>
 
</head>
<body>
<div id="images"></div>
<script>
$(document).ready(function () {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
	$.getJSON( flickerAPI, {tags: "sunshine",tagmode: "any",format: "json"},
	function(results) {
	//JQUERY function for iterating through the result set (a list of JSON objects are returned)
	//.each():Iterate over a jQuery object, executing a function for each matched element
	// i is a counter that automatically increments and item represents the current item from the result list
	$.each( results.items, function( i, item ) {
 
		$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
		// only show up to 10 images
		if ( i === 10 ) {
			return false;
		}
	}); //for each ....
  });// getJSON
}); // document ready
</script>
</body>
</html>

This example makes a request to the flickr api via the getJSON(). Specifically: we specify:

  • the URL to make the request to
  • the key-value pairs (our search criteria – that is sent to the server when processing the request) – in this query: we are asking for images that have the tag “sunshine”
  • the callback function which executes when we have a result set returned to us. The callback function has the argument “results” -> this is the returned set of JSON objects. The function will then go through each result -> using the JQuery “each” function and display to the screen as specified.

More on the .each():
Its Type: Function( Integer index, Element element )
A function to execute for each matched element.

Accessing and displaying Results from Flickr II ::

Ok – so we have gotten results from flickr – but the criteria was hardcoded. Let’s allow the user to select the criteria they are looking for. We can do this using html form elements, namely the input field an button:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Accessing FLICKR data using the jQuery.getJSON() </title>
<style>
img {
height: 100px;
float: left;
display:inline-block;
margin-left:10px;
margin-top:10px;
}
</style>
 <script src="jquery-3.3.1.min.js"></script>
 
</head>
<body>
 
<h1>
	Enter in the search criteria for flickr:
</h1>
<div>
<p>Type in a search keyword:</p>
<input type="text" id="searchText" value="search Item" />
<input type="button" value="Search!" id="searchButton" onclick="getFlicker()" />
</p>
</div>
<div id="images"></div>
<script>
function getFlicker()
{
 $("#images").empty();
 var searchItem = document.getElementById("searchText").value;
 /* using public feeds */
 /*https://www.flickr.com/services/feeds/docs/photos_public/*/
 var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
 // parameter is the search item
	$.getJSON( flickerAPI, {tags: searchItem,tagmode: "any",format: "json"},
	function(results) {
	//JQUERY function for iterating through the result set (a list of JSON objects are returned)
	//.each():Iterate over a jQuery object, executing a function for each matched element
	// i is a counter that automatically increments and item represents the current item from the result list
	$.each( results.items, function( i, item ) {
		$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
		// only show up to 10 images
		if ( i === 10 ) {
			return false;
		}
	}); //for each ....
  });// getJSON
}
</script>
</body>
</html>

Now: when you load the page – we just see an input field and button, only when the user types into the field and presses the button does the request get sent and consequently displayed.

Use Bing to do a search::

As a last example – which is slightly more complex – we will access the Bing API, enter a search term, send a request and retrieve and display the results:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
<!DOCTYPE html>
<html>
<head>
    <title>Bing Search v7 - Simple, show fewer results</title>
    <script src="jquery-3.3.1.min.js"></script>
    <style>
    html{
      width:100%;
    }
    body{
      width:100%;
      margin-left:20%;
 
    }
 
    label{
      display:inline-block;
      width:200px;
    }
    .formDiv{
      margin-top:10px;
      margin-bottom:10px;
    }
    .b{
      background: rgba(255,0,0,0.2);
      margin:0;
      padding:0;
      width:52%;
      padding:1%;
 
    }
    .wrapper{
      background:rgba(255,0,0,0.6);
      width:50%;
      overflow: hidden;
      padding:2%;
      margin:0'
    }
    h3{
      background:rgba(255,0,0,0.8);
      margin:0;
      padding:0;
      width:52%;
      padding:1%;
      color:rgba(0,0,0,0.8);
    }
    .res{
      margin-top:10px;
      background:rgba(0,0,255,0.6);
      color:white;
    }
    img {
    width: auto;
    height:100px;
    float: left;
    display:inline-block;
    margin-left:10px;
    margin-top:10px;
    }
 
    #contentFromBing{
      background:rgba(0,0,255,0.4);
      width:50%;
      overflow: hidden;
      padding:2%;
      margin:0;
      color: white;
    }
    </style>
</head>
<body>
 
<script type="text/javascript">
//https://docs.microsoft.com/en-us/azure/cognitive-services/bing-image-search/quick-start
//TO SIGN UP FOR A 30 day trial
//https://azure.microsoft.com/en-us/services/cognitive-services/bing-web-search-api/
 
    function getBing() {
 
       var searchItem = document.getElementById("searchText").value;
       var searchResultType = document.getElementById("searchType").value;
       console.log(searchResultType);
 
 
var t;
 if(searchResultType == "images")
  {
    t=" https://api.cognitive.microsoft.com/bing/v7.0/"+searchResultType+"/search?q=%27"+searchItem+"%27&%24format=json&%24top=1";
  }
else
  {
    t=" https://api.cognitive.microsoft.com/bing/v7.0/search?q=%27"+searchItem+"%27&%24format=json&%24top=1";
  }
        $.ajax({
            url: t,
            beforeSend: function(xhrObj){
                // Request headers
                // free limited 30-day trial license
                //https://datamarket.azure.com/account/keys
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","  f6f5e8560be841a5b6e09335b1c63ccc"); //replace value with your own key
            },
            type: "GET",
        })
        .done(function(data) {
       // console.log(data.value.length);
 
        $("#contentFromBing").empty();
        if(searchResultType == "images")
        {
          for(var i =0; i<data.value.length; i++ )
          {
        	    //console.log(data.value[i].thumbnailUrl)
        	    var imgSrc = data.value[i].thumbnailUrl;
              $("#contentFromBing").append('<div class="innerdiv"><img width="50" height="50" src="'+imgSrc+'" /></div>' );
          }
        }
        else
        {
        //https://docs.microsoft.com/en-us/azure/cognitive-services/bing-web-search/quick-start
           //console.log(data.webPages.value.length);
          for(var i =0; i<data.webPages.value.length; i++ )
        	{
        		//console.log(data.webPages.value[i])
        		if(data.webPages.value[i].displayUrl.startsWith("http") ==false)
        		{
              var t = "http://"+data.webPages.value[i].displayUrl;
              $("#contentFromBing").append('<a href='+t+'><p>'+t+'</a></p>');
        		}
        		else
        		{
        		    $("#contentFromBing").append('<a href='+data.webPages.value[i].displayUrl+'><p>'+data.webPages.value[i].displayUrl+'</a></p><p>'+data.webPages.value[i].snippet+'</p>');
        		}
 
        	}
        }
      })
      .fail(function() {
          alert("error");
      });
    }
 
</script>
 
<body>
<h3>Enter in the search criteria for bing:</h3>
<div class="wrapper">
<label>Type in a search keyword:</label>
<input type="text" id="searchText" value="search Item" />
<div class ="formDiv">
  <label>Select Result type:</label>
  <select id="searchType">
    <option value="search">Get Web Results</option>
    <option value="images">Get Image Results</option>
  </select>
</div>
</div>
<div class = "b">
<input type="button" value="Search!" id="searchButton" onclick="getBing()" />
</div>
 
<h3 class = "res">Result Set</h3>
<div id="contentFromBing">
</div>
</body>
</html>