\chapter{\index{JavaScript}JavaScript}
\section{Introduction to programming}
In order to tell a computer what to do, we use a special language, called a "programming" language. Like "human" languages, this is a set of instructions that are translated into codes that have specific meaning to the computer.

More formally, according to \url{http://en.wikipedia.org/wiki/Computer_programming}:
\begin{quote}
Computer programming (often shortened to programming) is a process that leads from an original formulation of a computing problem to executable programs. It involves activities such as analysis, understanding, and generically solving such problems resulting in an algorithm, verification of requirements of the algorithm including its correctness and its resource consumption, implementation (commonly referred to as coding) of the algorithm in a target programming language. Source code is written in one or more programming languages (such as C, C++, C\#, Java, Python, Smalltalk, JavaScript, etc.). The purpose of programming is to find a sequence of instructions that will automate performing a specific task or solve a given problem. The process of programming thus often requires expertise in many different subjects, including knowledge of the application domain, specialized algorithms and formal logic.
\end{quote}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
In a group execute the "marching orders" found in the book at \url{http://csunplugged.org/books}.
\end{Exercise}

\begin{Exercise}[difficulty=2, name={JavaScript Exercise}, counter=excjs]
Complete all 15 levels of \url{http://lightbot.lu}.
\end{Exercise}

\section{Getting started with JavaScript}
JavaScript is the programming language used to interact with the \index{Document Object Model (DOM)} Document Object Model (DOM) that the browser creates from HTML and CSS files. It thereby allows the programmatic control of the web page's appearance and behavior on the \emph{client side}. It is also used to access the powerful HTML5 Application Programming Interfaces (APIs) that make the development of full fledged web applications possible.

The official standard can be found at \url{http://www.ecma-international.org/publications/standards/Ecma-262.htm}.

\noindent\includegraphics[width=\linewidth]{javascript}

JavaScript is based on the ECMAScript language specification, the latest version of which is number 6 (cf. \url{http://www.ecma-international.org/news/Publication%20of%20ECMA-262%206th%20edition.htm}). However, browser support is still limited (cf. \url{https://kangax.github.io/compat-table/es6}).

An excellent JS book is at \url{http://chimera.labs.oreilly.com/books/1234000000262/index.html}.

A very insightful article on JavaScript can be found at \url{http://javascript.crockford.com/javascript.html}.

To find out what's new in ECMAScript 6 take a close look at the following resources:
\begin{itemize}
\item ES6 editor and examples at \url{http://www.es6fiddle.net}
\item Online book \url{http://exploringjs.com/es6}
\item Learn ES6 by doing \url{http://es6katas.org}
\item ES6 interactive guide \url{http://stack.formidable.com/es6-interactive-guide}
\item Learn the basics of the new features in ES6  \url{http://learnharmony.org}
\item Understanding ECMAScript 6 \url{https://leanpub.com/understandinges6/read}
\end{itemize}

Before we get started, open either the console of your browser or Firebug.

\begin{tabu}{|l|l|l|l|}
\hline & \textbf{Firefox} & \textbf{Chrome} & \textbf{Internet Explorer} \\ 
\hline Console & Shift + F2 & Ctrl + Shift + J or I & F12 \\
\hline Firebug & F12 & & \\
\hline
\end{tabu}
\vspace*{\baselineskip}

Firebug is only available for Firefox. You can install it via Tools -> Add-ons or via the firebug web site at \url{https://www.getfirebug.com}.

\noindent\includegraphics[width=\linewidth]{console1}
  
\begin{mdframed}[linecolor=red, linewidth=3pt, leftmargin=1cm, rightmargin=1cm]
You should always keep the console or Firebug open, as any error messages will only be visible there.
\end{mdframed}

\section{Adding JavaScript to HTML documents}
The HTML tag to include a script is, for obvious reasons, the \verb|<script>| tag. The user has the possibility to disable JavaScript in his browser. There's nothing we can do about this except detect it using the \index{<noscript>@\texttt{<noscript>}} \verb|<noscript>| tag and inform the user that our app won't run without JavaScript. In Firefox, you can disable JavaScript by going to the page \index{about:config@\texttt{about:config}} \verb|about:config| and setting \verb|javascript.enabled| to \verb|false|. Now run the example and turn JavaScript back on and rerun the example:

\noindent\url{\ftjs noscript1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/noscript1.html}}

\subsection{\label{External JS}External JavaScript}
The most common approach is to create a separate file with the extension \verb|.js| (the extension is not mandatory, but recommended) and include it in the HTML file. Here's an example:

\noindent\url{\ftjs js1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/js1.html}}

\noindent\url{\ftjs js1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/js1.js}}

The \index{strict mode} \verb|"use strict";| instruction turns on strict mode (cf. \ref{strict mode}), which we should always do in order to make our life easier and to write better quality code. You can put this instruction into the default JavaScript template of your IDE, so that you do not have to type it in every time (cf. \ref{NetBeans templates} or \ref{PhpStorm templates}). 

The \verb|<script>| tag can be placed into the document's head or body. Remember that your browser processes an HTML document from top to bottom. So if the script is put into the head, it is loaded and executed before the HTML body exists. If the script tries to access HTML elements, it will fail, as shown in this example (remember, you need to have the console or Firebug open to see the error):

\noindent\url{\ftjs js2.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/js2.html}}

\url{\ftjs js2.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/js2.js}}

Here is the error message you should see: \\
\noindent\includegraphics[width=\linewidth]{firebug1}
\vspace*{\baselineskip}

One solution to this problem is to include the script at the end of the HTML document, but this is not recommended, as it is difficult to see which script gets included. A cleaner approach is to have the script loaded in the head of the document but put all instructions that should be executed immediately into a function (don't worry, we'll look at those in detail in  \ref{JSFunctions}, but for now you just need to know that a function is a series of instructions that get executed when we "call" the function using its name) which gets run when the browser has either finished loading and parsing the initial HTML document, without waiting for stylesheets, images, and subframes to finish loading or when the full document has been loaded and parsed. To achieve the former, we use the \verb|DOMContentLoaded|(cf. \url{https://developer.mozilla.org/en/docs/Web/Events/DOMContentLoaded}) and for the latter the \verb|load| event (cf. \ref{Events} where we talk about events in detail):

\noindent\url{\ftjs js3.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/js3.html}}

\noindent\url{\ftjs js3.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/js3.js}}

\subsection{Embedded JavaScript}
If we have only a small script that we want to use in our document, we can embed it directly using the \verb|<script>| tag, like so:

\noindent\url{\ftjs js4.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/js4.html}}

We can embed JavaScript in the head and/or in the body part of the document.

\subsection{Inline JavaScript}
If we need to execute only one or very few instructions, for instance when a link is clicked, we can use JavaScript inline as an event handler (cf. \ref{Events}).

Here's a simple illustration using a clickable link:

\noindent\url{\ftjs js5.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/js5.html}}

\subsection{Combinations}
In the real world, you will often use combinations of some or all of the three methods, for instance an external script that defines functions, which are called via embedded or inline script.

Here is an example:

\noindent\url{\ftjs js6.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/js6.html}}

\noindent\url{\ftjs js6.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/js6.js}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a valid HTML5 document that includes an external script. The script defines a function that displays a message box with a text of your choice. Your \verb|<main>| element includes an image which, if clicked, displays the message box.
\end{Exercise}

\section{Comments}
In order to make our scripts easier to understand, it is a good idea to add comments that explain what the purpose of a piece of code is if it is not obvious. Comments should not repeat the code or explain trivialities. JavaScript provides single line comments using \verb|//| and multiline comments using \verb|/* */|. You have already seen examples of both in \ref{External JS}.

\section{Semicolons}
From \url{http://www.ecma-international.org/ecma-262/5.1/#sec-7.9}:
\begin{quotation}
Certain ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement) must be terminated with semicolons. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations.
\end{quotation}
In order to avoid needless errors, we'll always terminate the JS statements listed above with semicolons.

\section{\label{JSIO}Basic input and output}
\subsection{console.log}
The \verb|console| object provides access to the browser's debugging console, which we use to detect errors in our programs. For the details see \url{https://developer.mozilla.org/en-US/docs/Web/API/console} and \url{https://developer.mozilla.org/en-US/docs/Tools/Web_Console}.
Here is a simple example:

\noindent\url{\ftjs console1.html} \\
\url{\ftjs console1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/console1.js}}

\subsection{\texttt{document.write}}
\begin{mdframed}[linecolor=red, linewidth=3pt, leftmargin=1cm, rightmargin=1cm]
\textbf{DO NOT USE THIS METHOD} (cf.
\url{https://html.spec.whatwg.org/multipage/webappapis.html#document.write%28%29}).
\end{mdframed}


\verb|document.write| writes a given text verbatim into the document at the current position. Example:

\noindent\url{\ftjs document_write1.html} \\
\url{\ftjs document_write1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/document_write1.js}}

\subsection{\texttt{alert}}
In some of the previous examples we have already used the \verb|alert| method. This method is part of the global \verb|window| object, which we'll discuss in \ref{BOM}. Normally we would have to write \verb|window.alert| to use this method, but the browser considers \verb|window| as the default object, thereby allowing us to simply write the method name. \verb|alert| takes the text, quoted in \verb|""| or \verb|''|, as parameter and displays it in a dialog box, which will block the screen until the user confirms the message.

\subsection{\texttt{confirm}}
The \verb|confirm| method, just like \verb|alert|, displays a dialog box with a specified message, but with an OK and a Cancel button, so that the user has a choice. The method returns \verb|true| if the user clicked OK and \verb|false| if the user clicked Cancel. Example:

\noindent\url{\ftjs confirm1.html} \\
\url{\ftjs confirm1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/confirm1.js}}

\subsection{\texttt{prompt}}
\verb|prompt| is used to get input from the user. The first parameter specifies the text to display. The second parameter is optional and can be used to display a default value. Take a look at the example and experiment with it. Note the \verb|\'| in the prompt message. This is used to tell the browser that the apostrophe does not terminate the string but is to be displayed as such:

\noindent\url{\ftjs prompt1.html} \\
\url{\ftjs prompt1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/prompt1.js}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a valid HTML5 document with an embedded script that uses all the input and output functions seen in this section. Take the opportunity to experiment to your heart's content.
\end{Exercise}

\section{Constants}
If we want to use a specific immutable value throughout our script, we can declare it as a constant using \verb|const|. Constants have block scope, i.e. they are only visible within the block that they are defined. If we define a constant in the main part of our script it will be visible everywhere.  The advantage of using the constant compared to using the value directly is the ease with which we can change it.

For instance, if we decide that the player in our latest space shooter should have 5 lives instead of 3, we simply change the value of our constant. Without constant we would have to fiund all the occurrences of the value in our script and replace them individually, risking to accidentally change other values.

\begin{scriptsize}
\begin{minted}[tabsize=2, linenos=true, startinline=true]{js}
const LIVES = 3;
console.log(LIVES);
\end{minted}
\end{scriptsize}

\section{Variables}
A program spends most of its time manipulating some kind of data, e.g. integer and decimal (or floating point) numbers, text (called string) or other, potentially more complex, data types. The information we need, for internal calculations or for display to the user, has to be stored somehow. To store data, we use \emph{variables}. A variable is simply a place in computer memory where some information is stored.

To work with a variable we first need to declare it using the \verb|let| or \verb|var| keyword. The former has block scope whereas the latter has function scope. More on this difference later on. After declaration the variable value is undefined. We can store some information in it using the \verb|=| operator. Let's take a look at an example:

\noindent\url{\ftjs var1.html} \\
\url{\ftjs var1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/var1.js}}

\subsection{Variable names}
From \url{http://www.w3schools.com/js/js_variables.asp}:
\begin{itemize}
\item Variable names can contain letters, digits, underscores, and dollar signs.
\item Variable names must begin with a letter.
\item Variable names can also begin with \$ and \_.
\item Variable names are case sensitive (y and Y are different variables).
\item Reserved words (like JavaScript keywords) cannot be used as variable names.
\end{itemize}

It is recommended to use camelCase, e.g. \verb|firstFraction| instead of \verb|first_fraction| or \verb|firstfraction| etc. Please read the quick overview of JavaScript code conventions at \url{http://www.w3schools.com/js/js_conventions.asp}.

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Write JavaScript that declares a variable, gives it a value and writes its value to the console.
\end{Exercise}

\section{Data types}
JavaScript is a dynamically typed language, meaning that we can store any type of data in a variable or pass it as an argument to a function. This is in contrast to traditional programming languages such as C, C++, Java etc. Nevertheless, we need to be aware of the main data types that we will use. In our programs we can use the \verb|typeof| operator to determine the current type of a variable, as in this example:

\noindent\url{\ftjs types1.html} \\
\url{\ftjs types1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/types1.js}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a web page that declares four variables with the values \verb|'Text'|, \verb|123|, \verb|23.45| and \verb|false| respectively. It then generates an alert that displays the type of each one of the four variables.
\end{Exercise}

\subsection{\label{JSStrings}Strings}
A string is simply text, i.e. a sequence of one or more characters. Strings are always embedded within simple (\verb|'|) or double (\verb|"|) quotes. We can combine several strings using the \verb|+| operator, as shown in the examples below. Strings have a number of properties and methods that make working with them much easier. Study \url{http://www.w3schools.com/jsref/jsref_obj_string.asp} for a full reference with many examples.

Examples:

\noindent\url{\ftjs strings1.html} \\
\url{\ftjs strings1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/strings1.js}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Write a script that defines two string variables. The first one contains your first name, the second one your last name. Define a third variable that contains the first variable followed by a space followed by the second variable. Verify the result in the console.
\end{Exercise}

\subsection{\label{JSNumbers}Numbers}
JavaScript does not distinguish between integers and decimals. Numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.
This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63 (cf. \url{http://www.w3schools.com/js/js_numbers.asp}).
This has practical implications. Numbers have a number of properties and methods that make working with them much easier. Study \url{http://www.w3schools.com/jsref/jsref_obj_number.asp} for a full reference with many examples.

\noindent\url{\ftjs numbers1.html} \\
\url{\ftjs numbers1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/numbers1.js}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Write a script that defines two variables with the values 5 and 7.233453543 respectively. It then writes the sum with 2 decimals to the console.
\end{Exercise}

\subsection{Booleans}
A boolean value is either \verb|true| or \verb|false| (cf. \url{http://www.w3schools.com/js/js_booleans.asp}). This data type is used in conditions and comparisons. Example:

\noindent\url{\ftjs booleans1.html} \\
\url{\ftjs booleans1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/booleans1.js}}

\subsection{Conversions}
JavaScript provides several options to convert between data types.
To convert strings into numbers, we can put the \verb|+| operator in front of the string. If the string cannot be fully converted into a number, the result will be NaN, meaning not a number. To transform user input into a number, it is usually preferable to use \verb|parseInt| or \verb|parseFloat|. These functions take a string as input and return an integer or a decimal (float, shortcut for floating point number). The advantage of these functions is that even if there are non-numerical characters in the string, as long as there is at least one digit at the beginning of the string, they will return a number and simply ignore the other characters.
To convert anything into a string, we can use \verb|toString|, which is a method that every object has by default.
Let's look at a couple of examples:

\noindent\url{\ftjs conversions1.html} \\
\url{\ftjs conversions1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/conversions1.js}}

\subsection{Dates}
JavaScript provides a very useful \verb|Date| object to handle time and date information. Study
\begin{longtabu}{|X|}
\hline
\everyrow{\tabucline[0.5pt]{-}}
\url{http://www.w3schools.com/js/js_dates.asp} \\
\url{http://www.w3schools.com/jsref/jsref_obj_date.asp} \\
\url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date} \\
\end{longtabu}

\subsection{Math}
The \verb|Math| object offers a number of useful methods. Study \url{http://www.w3schools.com/js/js_math.asp} and \url{http://www.w3schools.com/jsref/jsref_obj_math.asp}.

\subsection{Regular expressions}
Regular expressions provide a very powerful means to search for patterns in strings. Study 
\url{http://www.w3schools.com/js/js_regexp.asp} and  \url{http://www.w3schools.com/js/js_regexp.asp}.

\section{Operators}
Study the JavaScript operator documentation on w3schools: \url{http://www.w3schools.com/js/js_operators.asp} and \url{http://www.w3schools.com/js/js_comparisons.asp}.

\subsection{\texttt{eval}}
\verb|eval| takes a string argument and interprets it as JavaScript code.

\noindent\url{\ftjs eval1.html} \\
\url{\ftjs eval1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/eval1.js}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Without using a computer, write down the answers to the following questions, then check your solutions using the console:

\noindent\url{\ftjs exop1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/exop1.js}}
\end{Exercise}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Write a valid HTML5 document that implements the following items:
\begin{enumerate}
\item The user is asked to enter two integers, which are saved in variables \verb|x| and \verb|y|.
\item Variable r contains the remainder of \verb|x| divided by \verb|y|.
\item Variable \verb|bool| contains \verb|true| if \verb|x| is bigger than \verb|y|, otherwise \verb|false|.
\item Variable \verb|s1| contains the text 'Hello', variable \verb|s2| the text 'guest'. Variable \verb|s| contains the text 'Hello guest!', which is created from \verb|s1| and \verb|s2| in a single statement.
\item A window displays the values of \verb|r|, \verb|bool| and \verb|s|.
\end{enumerate}
\end{Exercise}

\section{Conditional statements}
See \url{http://www.w3schools.com/js/js_if_else.asp}.

\subsection{\texttt{if}}
Oftentimes the behavior of our program depends on a condition. For example, if we have developed a social network and we want to congratulate the user on his birthday, we first need to verify the condition of the user's birthday being true. Let's look at a couple of examples:

\noindent\url{\ftjs if1.html} \\
\url{\ftjs if1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/if1.js}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a valid HTML5 document that asks the user a question and then informs him whether his answer was correct or not.
\end{Exercise}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a valid HTML5 document that asks for a grade between 1 and 60 and then tells the user whether it is very bad (<10), bad (<20), insufficient (<30), sufficient (<40), good (<50), very good (<60) or excellent (60).
\end{Exercise}

\subsection{switch}
Another instruction that can be used if there are many alternatives to choose from is \verb|switch|. A detailed explanation can be found at \url{http://www.w3schools.com/js/js_switch.asp}. Here's is an example:

\noindent\url{\ftjs switch1.html} \\
\url{\ftjs switch1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/switch1.js}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a valid HTML5 document that displays the current day of the week in text form using \verb|switch|.
\end{Exercise}

\section{Loops}
Loops are used to execute a block of, i.e. one or several, statements, several times. JavaScript provides the \verb|for|, \verb|while|, \verb|for in| and \verb|do while| loops. Each loop consists of a head and a body part.

\subsection{\texttt{for}}
The \verb|for| loop head specifies the start value, a condition and what should be done after each iteration of the body. This type of loop is the preferred choice if we know the number of iterations in advance. We already saw an example in \ref{JSNumbers}. Let's study a couple more examples:

\noindent\url{\ftjs for1.html} \\
\url{\ftjs for1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/for1.js}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Write a script that calculates and displays the factorial of a positive integer stored in the variable x. Remember, $!$ is the mathematical symbol for factorial, $x! = x * (x-1)!$ and $1! = 1$.
\end{Exercise}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
The user is asked for a number. If the number is not positive, nothing happens. Otherwise, a count down, starting at the number and counting down to 0, is displayed using a message box.
\end{Exercise}

\subsection{\texttt{while}}
The \verb|while| loop head only specifies the condition that needs to be true for the loop body to be executed. The condition can be any boolean expression, i.e. we do not necessarily need a counter variable. Let's look at an example:

\noindent\url{\ftjs while1.html} \\
\url{\ftjs while1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/while1.js}}

\begin{Exercise}[difficulty=2, name={JavaScript Exercise}, counter=excjs]
Write a script that calculates the greatest common divisor (gcd, cf. \url{http://en.wikipedia.org/wiki/Greatest_common_divisor}) of two given positive integers stored in variables \verb|a| and \verb|b|. A simple method to do this is to realize that the gcd cannot be bigger than the smallest of the two numbers. So that's your starting point. Now you can find the gcd by testing whether the smallest of \verb|a| and \verb|b| divides both. If not, you subtract 1 from that value and test again. Your loop must terminate, because 1 is a divisor of every number.
\end{Exercise}

\subsection{\texttt{for in}}
\verb|for in| loops through the enumerable properties of an object and includes the enumerable properties of the prototype chain (cf. \ref{JSObjects}).

\noindent\url{\ftjs forin1.html} \\
\url{\ftjs forin1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/forin1.js}}

You should not use \verb|for in| to loop through an array, as the following example inspired by "Effective JavaScript" p. 132 shows:

\noindent\url{\ftjs forin2.html} \\
\url{\ftjs forin2.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/forin2.js}}

\subsection{\texttt{do while}}
This is identical to the \verb|while| loop, except that the body of \verb|do while| is always executed at least once, as the condition is only checked after the execution instead of before.

\section{Jumps and exceptions}
Jump statements instruct the JavaScript interpreter to jump to a different source code location.

\subsection{Labeled statements}
A JavaScript statement can be labeled by writing the label followed by a colon.

\subsection{\texttt{break}}
Used alone, \verb|break| causes the innermost enclosing loop or switch statement to exit immediately. If followed by a label, it terminates the enclosing statement that has the specified label.
Take a close look at these examples:

\noindent\url{\ftjs break1.html} \\
\url{\ftjs break1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/break1.js}}

\subsection{\texttt{continue}}
\verb|continue| is similar to \verb|break|, except that it does not exit the loop but restarts it at the next iteration, i.e. it terminates only the current iteration, not the whole loop.
Example:

\noindent\url{\ftjs continue1.html} \\
\url{\ftjs continue1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/continue1.js}}
\subsection{Exception handling}
Often our programs rely on the user to provide reasonable input. But what happens if the user provides invalid input? For instance, we have a function that calculates the product of all given parameters, assuming they are all numbers. If one of the parameters is a string, our script not perform as expected. That's not very professional and chances are, our users won't like it. A better way is to throw an exception using the \verb|throw| instruction and catch it using \verb|try catch finally|. In the \verb|try| block we put the code that is at risk of breaking, for instance on wrong user input. In the \verb|catch| block we put the code that should be executed if something went wrong in the \verb|try| block, i.e. an exception occurred. The \verb|finally| block is optional and will always be executed as the final block. JavaScript has a built-in \verb|Error| object (cf. \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error}), that serves to signal an error. Let's study an example:

\noindent\url{\ftjs exceptions1.html} \\
\url{\ftjs exceptions1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/exceptions1.js}}
 
\section{\label{JSFunctions}Functions}
A function is a block of code that is executed by "calling" the function. Functions are of fundamental importance in software development, as they permit to reuse code, i.e. we solve a problem once and can then use the solution as often as we want without having to reinvent the wheel.

\subsection{Functions}
A function is defined using the \verb|function| keyword, followed by parentheses \verb|()|, followed by curly brackets \verb|{}|. A function can take one or several parameters, which represent information that is given to the function by the caller. \textbf{Parameters of primitive types are passed by value, whereas objects are passed by reference}.

Within the curly brackets we find the body of the function, i.e. the code that is executed when the function is called. A function can return an object using the \verb|return| keyword. Please note that \verb|return| does 2 things:
\begin{enumerate}
\item Returns the given object, or nothing if no object is provided.\item Terminates the function. This means that any instructions following \verb|return| will not be executed.
\end{enumerate}

JavaScript functions have a built-in arguments object, which contains an array of the arguments used when the function was called.

Also note that a function can be called before its declaration. This is called hoisting.

Let's study a couple of examples:

\noindent\url{\ftjs functions1.html} \\
\url{\ftjs functions1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/functions1.js}}

\subsection{Arrow functions}
An arrow function is created using \verb|=>|. It means that the value in the parentheses, if any, is passed as parameter to the block of code that the arrow is pointing to. An arrow function is defined like a variable.

Contrary to functions, which are read at compile-time, arrow functions are read at run-time. Therefore they must be defined in the code before they can be called.

Also contrary to a function, an arrow function does not have an \verb|arguments| object (cf. point 18.a in \url{http://www.ecma-international.org/ecma-262/6.0/#sec-functiondeclarationinstantiation}).

\noindent\url{\ftjs functions1b.html} \\
\url{\ftjs functions1b.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/functions1b.js}}

\begin{mdframed}[linecolor=red, linewidth=3pt, leftmargin=1cm, rightmargin=1cm]
A major difference between a function and an arrow function is that in the case of a function, the scope is local whereas in the case of an arrow function, the scope is the surrounding code.
\end{mdframed}

The following example illustrates this difference (cf. \ref{this}):

\noindent\url{\ftjs functions1c.html} \\
\url{\ftjs functions1c.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/functions1c.js}}

\subsection{Variable scope}
It is important to understand the concept of variable scope. A local variable, i.e. a variable that is declared inside the body of a function using the \verb|let| or \verb|var| keyword is called a local variable and only exists within the function body. A variable declared outside a function (with or without \verb|let| or \verb|var|) or a variable implicitly declared without \verb|let| or \verb|var| inside a function is a global variable, i.e. it exists even after the function execution has finished. Furthermore, if a global variable \verb|x| is declared and inside a function we declare a local variable \verb|x|, the local \verb|x| will hide the global \verb|x|, meaning that when we use \verb|x| in the function, it will be the local and not the global one.

\begin{mdframed}[linecolor=red, linewidth=3pt, leftmargin=1cm, rightmargin=1cm]
{\textbf{If you declare a variable without the \texttt{var} or \texttt{let} keyword, it will always be global, even if declared within a function! This can lead to errors that are hard to detect and should be avoided.}}
\end{mdframed}

Let's illustrate this with a few examples:

\noindent\url{\ftjs functions2.html} \\
\url{\ftjs functions2.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/functions2.js}}

Note in the examples above that we called function f1 before its declaration. This behavior is possible because of function hoisting.

\subsection{Anonymous functions}
We can pass a nameless function as a parameter to a function or assign it to a variable. This will be particularly useful when we deal with event handlers as we'll see later on.

Here is an example of an anonymous function:

\noindent\url{\ftjs functions3.html} \\
\url{\ftjs functions3.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/functions3.js}}

\noindent\url{\ftjs functions4.html} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/functions4.html}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Write a function \verb|sumUpTo| that takes a positive integer as parameter and returns the sum of all integers from 1 up to this parameter.
\end{Exercise}

\begin{Exercise}[difficulty=2, name={JavaScript Exercise}, counter=excjs]
Improve the previous function so that if the parameter is not a positive integer, the function returns false.
\end{Exercise}

\begin{Exercise}[difficulty=2, name={JavaScript Exercise}, counter=excjs]
Write a function \verb|createTable| that takes two parameters, \verb|w| and \verb|h|. The function writes an HTML table with \verb|w| columns and \verb|h| rows. Put a random number from [1, 9] into each cell. Validate the result.
\end{Exercise}

\begin{Exercise}[difficulty=2, name={JavaScript Exercise}, counter=excjs]
Write a function \verb|average| that returns the average of all the parameters provided. The function can take any number of parameters, including none. If no parameters are provided or if any of the parameters is not a number, the function returns \verb|false|. Analyze and verify your function in the debugger.
\end{Exercise}

\section{Debugging}
"Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program" (cf. \url{http://en.wikipedia.org/wiki/Debugging}).

The short video at \url{http://youtu.be/0zWiq8FB3Xg} shows how this works in practice using the following HTML document:

\noindent\url{\ftjs debug1.html} \\
\url{\ftjs debug1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/debug1.js}}

\section{Arrays}
Arrays are ordered value collections. Each value or element has its position, which is called index. The index of the first element is 0 and the position of the last element is the length of the array minus 1. The index is a 32 bit number, so the maximum number of elements in an array is $2^{32} - 1$. Arrays are dynamic and we do not have to specify any initial size.

It is essential to study \url{http://www.w3schools.com/js/js_arrays.asp} and \url{http://www.w3schools.com/js/js_array_methods.asp}.

\subsection{Creating and iterating}
We create an array either as an array literal, which is the recommended way, or using the Array constructor. The latter method is conducive to errors, as explained in the example:

\noindent\url{\ftjs array_creation.html} \\
\url{\ftjs array_creation.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/array_creation.js}}

It is important to note that arrays are objects. Therefore the \verb|in| operator will use all enumerable properties of the object itself and its prototype, as described in \ref{ObjectPropertyTesting}. This will include methods that have been added to the prototype unless they are not enumerable. Furthermore, the ECMAScript specification does not fix the order in which the \verb|in| operator returns elements. If element order is important, we should use a standard \verb|for| loop to iterate through an array. If order does not matter, but we cannot guarantee that the array prototype is not polluted with enumerable properties, we should include a test to filter these, as shown in the examples above.

\subsection{Adding and deleting}
\noindent\url{\ftjs array_add_delete.html} \\
\url{\ftjs array_add_delete.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/array_add_delete.js}}

\subsection{Multidimensional arrays}
An array element can be another array. So we can easily create multidimensional arrays like so:
\noindent\url{\ftjs array_multidim.html} \\
\url{\ftjs array_multidim.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/array_multidim.js}}

\subsection{Methods}
We have already seen \verb|push| and \verb|pop| methods. A nearly complete reference with examples can be found at \url{http://www.w3schools.com/jsref/jsref_obj_array.asp}.
The following methods are missing in the reference and therefore listed here.

\subsubsection{\texttt{forEach}}

\subsubsection{\texttt{map}}
This method passes each element of the array which is passed as first parameter to the function specified as second parameter. The result is an array containing the values returned by the function.

\noindent\url{\ftjs array_map.html} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/array_map.html}}

\subsubsection{\texttt{filter}}

\subsubsection{\texttt{every} and \texttt{some}}

\subsubsection{\texttt{reduce} and \texttt{reduceRight}}

\subsubsection{\texttt{indexOf} and \texttt{lastIndexOf}}

\subsubsection{\texttt{isArray}}
\noindent\url{\ftjs array_isArray.html} \\
\url{\ftjs array_isArray.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/array_isArray.js}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Write a script that creates an array containing the numbers from 1 to 10. Add a function \verb|displayArr| that iterates over the array and writes each array element to the console. Call \verb|displayArr|, remove the last element and call \verb|displayArr| again.
\end{Exercise}

\begin{Exercise}[difficulty=2, name={JavaScript Exercise}, counter=excjs]
Write a script that creates a matrix, i.e. a 2-dimensional array of 10 rows, each containing 20 elements. Use \verb|Math.random| (cf. \url{http://www.w3schools.com/jsref/jsref_random.asp}) to give a random value to each array element. Write a function \verb|displayMat| that displays the matrix, which is passed as parameter in a readable way, i.e. each row on a new line.
\end{Exercise}

\section{\label{JSObjects}Objects}
In JavaScript, anything that is not a string, number, boolean, null or undefined is an object. Objects are collections of properties (cf. \url{http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.3}). They allow us to regroup data and functions that belong together under one name and to reuse them. One purpose is the representation of real world objects. A good introduction can be found at \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects}.

JS comes with a number of standard built-in objects, details of which can be found at \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects}.

\subsection{Prototypes}
Most objects are derived from another object. This other object is called prototype in JavaScript. \verb|Object| is the basic object in JavaScript from which normally all other objects inherit, directly or indirectly. To determine the prototype of an object, we use \verb|Object.getPrototypeOf()|, where we pass the object as parameter.


\subsection{Object creation}
There are three ways to create objects.

\subsubsection{as literals}
From "JavaScript The Definitive Guide" p. 117: "An object literal is a comma-separated list of colon-separated name:value pairs, enclosed within curly braces."  \verb|this| refers to the object itself, whose property we want to use. Object literals are often used to avoid declaring a large number of global variables and functions by creating a namespace. This helps to document that a set of properties belong together and serve a common purpose.  When we create an object literal, its prototype is \verb|Object.prototype|. \ref{WMOTUInvadersOO} provides a sample application. 
Examples:

\noindent\url{\ftjs objects_literals.html} \\
\url{\ftjs objects_literals.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/objects_literals.js}}

\subsubsection{from a constructor with \texttt{new}}
\verb|new| must be followed by a \textbf{constructor}, which is a function that initializes the newly created object. As noted above, \verb|this| refers to the object itself, whose property we want to use. The advantage of this approach compared to the previous one is that we can create as many objects as we like using the same constructor. When we use a constructor, the prototype is the \verb|prototype| property of the constructor.
Example:

\noindent\url{\ftjs objects_new.html} \\
\url{\ftjs objects_new.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/objects_new.js}}

\subsubsection{from a prototype with \texttt{Object.create()}}
Almost all JavaScript objects inherit the properties of another object, their prototype.
\verb|Object.create| is a method that allows us to create a new object with a given prototype.

\noindent\url{\ftjs objects_prototypes.html} \\
\url{\ftjs objects_prototypes.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/objects_prototypes.js}}

It is important to understand the difference between a constructor and a prototype. The prototype of an object contains all the properties that are common to all objects that have this prototype. They exist only once in the browser memory. Thus any changes to any of these properties are automatically reflected in all the objects that inherit from this prototype! Take a close look at the following examples:

\noindent\url{\ftjs objects1.html} \\
\url{\ftjs objects1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/objects1.js}}

\subsection{\label{this}\texttt{this}}
Mastery of the \verb|this| keyword is a key requirement for understanding JS objects. You should therefore study the excellent explanation at \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this}.

\subsection{Getting and setting properties}
To get or set properties of an object we can either use the dot (\verb|.|) or the square bracket (\verb|[]|) operators. There is an important difference between these two: when using the dot operator, the right-hand must be an identifier, i.e. the name of the property. This cannot be a programmatically generated dynamic value. When using the square bracket operator, the value between the brackets must be an expression that evaluates to a string or to something that can be converted to a string. This opens up endless possibilities, so let's look at a few examples:

\noindent\url{\ftjs objects_access.html} \\
\url{\ftjs objects_access.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/objects_access.js}}

\subsection{Deleting properties}
\verb|delete| removes a property from an object. If you invoke \verb|delete| on a prototype property, then all objects inheriting from this prototype lose this property.

\noindent\url{\ftjs objects_delete.html} \\
\url{\ftjs objects_delete.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/objects_delete.js}}

\subsection{\label{ObjectPropertyTesting}Testing properties}
We have different options to test whether an object has a given property:
\begin{enumerate}
\item The \verb|in| operator requires the name of a property as a string on its left and an object on its right side. It returns true if the object has an enumerable own or inherited property by that name (cf. \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in}).
\item \verb|Object.keys(obj)| returns an array of a given object's own enumerable properties (cf. \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys}).
\item \verb|Object.getOwnPropertyNames(obj)| returns an array of all properties (enumerable or not) found directly upon a given object (cf. \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames}).
\item The \verb|hasOwnProperty()| of an object checks whether the object has a property of the given name. It does not consider inherited properties for which it returns false (cf. \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty}).
\item \verb|propertyIsEnumerable()| returns a Boolean indicating whether the specified property is enumerable (cf. \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable}).
\end{enumerate}

The following example illustrates the different approaches:

\noindent\url{\ftjs objects_test.html} \\
\url{\ftjs objects_test.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/objects_test.js}}

\subsection{Object attributes}
Every object has \verb|prototype|, \verb|class| and \verb|extensible| attributes.

\subsubsection{\texttt{prototype}}
This attribute specifies the object's parent, i.e. the object that it inherits from. As we've seen above, for object literals the prototype is \verb|Object.prototype|, for objects created with \verb|new| the prototype is the value of the constructor's prototype property and for objects created with \verb|Object.create|, the prototype is the first parameter passed to this method.

Every object has an \verb|isPrototypeOf| method, which checks whether the object if the prototype of another object passed as parameter.

\subsubsection{\texttt{class}}
This internal read-only attribute tells us the type of the object. This attribute can take one of the following values: "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp" or "String".

\subsubsection{\texttt{extensible}}
This attribute determines whether new properties can be added to the object. \verb|Object.isExtensible()| tells us whether an object is extensible or not. \verb|Object.preventExtensions| allows us to make an object nonextensible. \\

Here is an example that illustrates the three object attributes:

\noindent\url{\ftjs objects_attributes_prototype.html} \\
\url{\ftjs objects_attributes_prototype.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/objects_attributes_prototype.js}}


\subsection{Property attributes}
Each object property has, in addition to its value, the following three attributes:
\begin{enumerate}
\item  \verb|configurable|: if this is false, 
\item \verb|enumerable|
\item \verb|writable|. 
\end{enumerate}

Using \verb|Object.defineProperty(obj, prop, descriptor)| we can set these attributes (cf.
\url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty}).

\subsection{Closures}
From \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures}: "A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created."
Study the MDN article, it explains the subject in detail with good examples.
Then take a look at \url{http://bonsaiden.github.io/JavaScript-Garden}.

\noindent\url{\ftjs lexical_scoping1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/lexical_scoping1.html}}

In ECMAScript 6 however we can simply use function expressions, where the scope inside the function is the same as the one outside, and thereby avoid closures in most cases.

\noindent\url{\ftjs lexical_scoping2.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/lexical_scoping2.html}}

\subsection{Private instance and prototype members}
\url{http://www.crockford.com/javascript/private.html}

Here is a more advanced example, illustrating how we can have both private prototype and private object members and inheritance:

\noindent\url{\ftjs objects2.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/objects2.html}}

\subsection{\texttt{call}, \texttt{apply} and \texttt{bind}}
Given that functions are objects in JavaScript, these three methods allow us to call a function as if it were a method of another object. Detailed descriptions of the Function object and examples can be found at \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function}.

\noindent\url{\ftjs indirect1.html} \\
\url{\ftjs indirect1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/indirect1.js}}

\subsection{\texttt{Object}}
The global \verb|Object| object has a number of properties. The details can be found at \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object}. For instance, if we want to determine the number of an object's own enumerable properties, we can use \verb|Object.keys(object)|.

\subsection{The \texttt{Proxy} object}
\url{https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Proxy}

\section{\label{Events}Events}
So far we have seen how to write scripts that execute sequentially, i.e. instructions are processed one after the other. In real life, however, our browser spends most of its time waiting for something to happen, e.g. a key or mouse button is pressed, a picture is loaded, a given timespan has expired, etc. This "something" is called an event in JavaScript. See the references below for the full list of available events.

For our scripts to be able to react to an event, we need to declare functions, called event listeners or handlers, that are invoked by the browser when a specific event occurs. Our handler will be automatically passed an \verb|Event| object (cf. references).

\begin{tabu}{|X|}
\hline
%\everyrow{\tabucline[0.5pt]{-}}
\url{http://www.w3schools.com/jsref/dom_obj_event.asp} \\ \hline
\url{https://developer.mozilla.org/en-US/docs/Web/Events} \\ \hline
\url{https://developer.mozilla.org/en-US/docs/Web/API/Event} \\ \hline
\url{http://www.javascriptkit.com/script/script2/xeye.shtml} \\ \hline
\end{tabu}

\subsection{Registering event listeners}
In order to tell the browser what it should do if an event occurs, we need to register an event listener. There are 3 ways to do this.

\subsubsection{\texttt{addEventListener}}
\sloppypar The recommended way is to use the \verb|addEventListener| method (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener}) of the object that will be the target of the event. The first parameter is a string containing the name of the event, the second one will be either an anonymous function or the name (without apostrophes) of the function that will handle the event. The optional third parameter allows to have the listener triggered already in the capture phase as described below. We can register several listeners for the same event using this method:

\noindent\url{\ftjs event_listeners1.html} \\
\url{\ftjs event_listeners1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/event_listeners1.js}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a page that triggers an alert when the user tries to resize the browser window.
\end{Exercise}

\subsubsection{Object property}
Another option for event listener registration is the use of the corresponding object property. The name of this property is "on" followed by the event name, e.g. "onclick", "onload" etc. If a handler for this event has already been registered using this approach, it will be replaced:

\noindent\url{\ftjs event_listeners2.html} \\
\url{\ftjs event_listeners2.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/event_listeners2.js}}

\subsubsection{HTML attribute}
The third and least preferable registration method is the 
use of an HTML attribute. This way should be avoided as it violates the separation of content and behavior:

\noindent\url{\ftjs event_listeners3.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/event_listeners3.html}}

\subsubsection{Invocation order}
Handlers registered via an object property or HTML attribute are always executed first. Handlers registered with \verb|addEventListener| are called in the order in which they were registered.

\subsection{Event flow}
The chart at \url{http://www.w3.org/TR/DOM-Level-3-Events/#dom-event-architecture} illustrates the three event phases: capture, target and bubble. If the target of an event is a standalone object (e.g. window), only the event handler on that object will be triggered. If the target object is a tree, for instance the document element, most, but not all, events bubble up the tree as illustrated in the chart. This avoids the need to register event handlers on lots of different elements. We can register a single event handler at the top of the tree, which can deal with the events triggered on its children. 
If we set the third parameter of \verb|addEventListener| to true, events are captured before reaching the target object. As seen in the chart, this is the inverse process of bubbling. It provides an opportunity for the parent objects to analyze the event before it reaches the target. This is useful in certain situations, for instance for the implementation of drag and drop, as we'll see in \ref{DrandAndDrop}:

\noindent\url{\ftjs events1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/events1.html}}

The following example is identical to the previous one, except that the third parameter of \verb|addEventListener| is not set:
\noindent\url{\ftjs events2.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/events2.html}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Compare the behavior of these two scripts. What do you observe? How do you explain your observations?
\end{Exercise}

\subsubsection{Preventing event propagation and/or default actions}
In some cases we might want to prevent the default action for a given event to occur, for instance, in order to prevent a form from being submitted when the user clicks the submit button. For this purpose we can call the \verb|preventDefault| method. We can also stop event propagation using \verb|stopPropagation|.
In most cases our event handlers will not return a value. However, if we want to prevent default action and stop propagation, we can return false in our event handler. This works only if the event handler has been registered as an object property or an HTML attribute. With \verb|addEventListenener| we can call the \verb|preventDefault| and/or \verb|stopPropagation| methods:

\noindent\url{\ftjs event_cancellation1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/event_cancellation1.html}}

\subsection{Keyboard events}
It is important to understand the difference between the three keyboard events \verb|keydown|, \verb|keypress| and \verb|keyup|: When you press a key down, a \verb|keydown| event is triggered, followed by a \verb|keypress| event. If you keep the key pressed, \verb|keypress| events will continue to be generated at regular time intervals until you release the key, in which case a \verb|keyup| event will be triggered. The following program displays all the attributes of the key events:

\noindent\url{\ftjs keyevents1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/keyevents1.html}}

Here is the same program, but instead of hard coded HTML tables, they are generated using JavaScript. This shows how we can modify the DOM (cf. \ref{DOM}). The result is 75 lines instead of 176:

\noindent\url{\ftjs keyevents1_optimized.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/keyevents1_optimized.html}}

To determine the code for a specific key, take a look at the following links:
\begin{longtabu}{|X|}
\hline
\everyrow{\tabucline[0.5pt]{-}}
\url{http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes} \\
\url{https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.keyCode} \\
\url{http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731\%28v=vs.85\%29.aspx} \\
\end{longtabu}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a page that generates an alert saying "Hi!" when the h key is pressed.
\end{Exercise}

\subsection{\texttt{unload} and \texttt{beforeunload}}
If we want to have some code executed when a user navigates away from our page, we can use the \verb|beforeunload| (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload}) or the \verb|unload| (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onunload}) events.

Here is a simple example:

\noindent\url{\ftjs beforeunload.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/beforeunload.html}}
\noindent\url{\ftjs beforeunload.php}
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/beforeunload.php}}

\subsection{\texttt{error}}
When we include images in our HTML document, which cannot be found by the browser, the browser will display an ugly icon. In Firefox we can solve this issue by setting the alt attribute to the empty string. To solve the issue for all browsers, we can handle the \verb|error| event, like so (test it in Chrome and Firefox to see the difference):

\noindent\url{\ftjs onerrorhtml}
{\scriptsize\inputminted[tabsize=2,linenos=true]{html}{JS/onerror.html}}

\section{\index{Document Object Model (DOM)}\label{DOM}Document Object Model (DOM)}
From \url{https://developer.mozilla.org/en-US/docs/Glossary/DOM}: "The Document Object Model (DOM) is an API defined by the W3C to represent and interact with any HTML or XML document. 
The DOM is a model of an HTML or XML document that is loaded in a web browser. It represents a document as a tree of nodes, where each node represents a portion of the document, such as an element, a portion of text or a comment.
The DOM is one of the most used APIs on the web because it allows code running in a web browser to access and interact with every node in the document.  Nodes can be created, moved and changed. Event listeners can be added to nodes. Once a given event occurs all of its event listeners are triggered."

We have already looked at the DOM in several instances using the browser console or Firebug.

\pagebreak
Here is what the DOM of a very basic HTML document looks like:

\noindent\includegraphics[width=\linewidth]{DOM}

A basic introduction can be found at \url{http://www.w3schools.com/js/js_htmldom.asp}.

\verb|HTMLElement| represents any HTML element. Specific elements are children of this object. For instance, a div element is represented via an \verb|HTMLDivElement| object (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model}).

\verb|HTMLDocument| defines some specific properties that are often quite handy. \verb|document.body| is the \verb|<body>|, \verb|document.head| the \verb|<head>| and \verb|document.documentElement| the root, i.e. \verb|<html>| element of the document.

\subsection{Properties and methods of the HTML DOM Element Object}
At \url{http://www.w3schools.com/jsref/dom_obj_all.asp} you can find a list of the properties and methods of the HTML DOM Element object with examples, which is very helpful.

\subsection{Selecting DOM elements}
Before we can change a DOM element in JavaScript, we need to select it, i.e. we need to get a pointer to the element. For this purpose, the \verb|document| object allows us to select an element by id, name, tag, CSS class or selector.

\subsubsection{\texttt{document.getElementById}}
This method takes a string parameter specifying the ID of the element that we want.

\noindent\url{\ftjs getElementById.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/getElementById.html}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a web app with a button. Clicking on the button displays an alert with the text "You clicked me!".
\end{Exercise}

\begin{Exercise}[difficulty=3, name={JavaScript Exercise}, counter=excjs]
Write a function that takes any number of string arguments representing element ids. For each ID the function retrieves the corresponding element. If any of the ids is invalid, an error message is thrown, otherwise the function returns an object that maps each id to its DOM element. 
\end{Exercise}

\subsubsection{\texttt{document.getElementsByName}}
This method takes a string parameter specifying the name of the element that we want and returns a \verb|NodeList| object, which we can access using indices, like arrays (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/NodeList}). Remember that the \verb|name| attribute is used during form submission to send data to the server. Not every HTML element can have a \verb|name| attribute.

\noindent\url{\ftjs getElementsByName.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/getElementsByName.html}}

\subsubsection{\texttt{document.getElementsByTagName}}
This method works like the previous one, except that the parameter is the HTML tag for which we want to select all elements.

\noindent\url{\ftjs getElementsByTagName.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/getElementsByTagName.html}}

\begin{Exercise}[difficulty=3, name={JavaScript Exercise}, counter=excjs]
Create a web app with 3 buttons. You may not use \verb|getElementById|. Clicking on any of the buttons displays an alert with the text "You clicked button number " followed by the number of the button (1-3).
For experts: enhance your script so that it works for any number of buttons.
\end{Exercise}

\subsubsection{\texttt{document.getElementsByClassName}}
This method works like the previous two, except that the parameter is the CSS class for which we want to select all elements.

\noindent\url{\ftjs getElementsByClassName.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/getElementsByClassName.html}}

\subsubsection[\texttt{document.querySelector} and \protect\\ \texttt{document.querySelectorAll}]{\texttt{document.querySelector} and \texttt{document.querySelectorAll}}
These methods work like the previous three, except that the parameter is the CSS selector for which we want to select all elements (cf. \url{http://www.w3.org/TR/selectors-api}). \verb|querySelector| returns the first element that matches the given CSS selector, whereas \verb|querySelectorAll| returns a \verb|NodeList| object with all the matching elements.
These are the most powerful selectors available. We can use the whole gamut of CSS selectors described in \url{http://www.w3schools.com/cssref/css_selectors.asp}.

\noindent\url{\ftjs querySelector.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/querySelector.html}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a web page with 3 \verb|article| tags, two of which belong to class \verb|special|. Using JavaScript, change the background color of the articles that are special.
\end{Exercise}

\subsubsection{Direct access via the \texttt{document} object}
We can directly access the following HTML objects (and object collections):
\begin{itemize}
\item \verb|document.anchors|
\item \verb|document.body|
\item \verb|document.documentElement|
\item \verb|document.embeds|
\item \verb|document.forms|
\item \verb|document.head|
\item \verb|document.images|
\item \verb|document.links|
\item \verb|document.scripts|
\item \verb|document.title|
\end{itemize}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Go to one of the well known web pages. Open the console and take a look at the HTML objects listed above. Change the title of the page.
\end{Exercise}

\subsection{\label{DOMTraversal}Traversing the DOM}
Depending on what we want to do, we can traverse the DOM as a node or as an element tree.

\subsubsection{Node trees}
From \url{http://www.w3schools.com/jsref/dom_obj_all.asp}:
"In the HTML DOM, everything is a node:
\begin{itemize}
\item The document itself is a document node.
\item All HTML elements are element nodes.
\item All HTML attributes are attribute nodes.
\item Texts inside HTML elements are text nodes.
\item Comments are comment nodes."
\end{itemize}

The link above provides extensive information on the \verb|NodeList| object's methods and properties. In particular, we can determine a node's type via the \verb|nodeType| property (cf. \url{http://www.w3schools.com/jsref/prop_node_nodetype.asp}).

\noindent\url{\ftjs DOM_nodes.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/DOM_nodes.html}}

\subsubsection{Element trees}
From \url{https://developer.mozilla.org/en-US/docs/Web/API/element}: "The Element interface represents an object within a DOM document." Text and comment nodes are not treated as objects in this context and are ignored. This API allows us therefore to traverse the DOM element tree, without bothering with text and comments.

The \verb|children| property of an element is particularly useful, as it contains an array of all of its HTML element children.

\noindent\url{\ftjs DOM_elements.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/DOM_elements.html}}

\subsection{Getting and setting attributes}

\subsubsection{as element properties}
The attributes of HTML elements are available as properties of the corresponding HTMLElement in JavaScript.
However, whereas HTML attributes are not case sensitive, JavaScript properties use camel case (cf. \url{https://en.wikipedia.org/wiki/CamelCase}). For instance the \verb|usemap| attribute of an \verb|img| element can be accessed via the \verb|useMap| property. There are two exceptions: given that some attribute names are reserved words in JavaScript, the property name has an "html" prefix, for instance the \verb|for| attribute can be accessed via the \verb|htmlFor| property. The exception to the exception is the \verb|class| attribute, which can be accessed via the \verb|className| property.

\noindent\url{\ftjs DOM_attributes1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/DOM_attributes1.html}}

Here is an example of how to scroll to the end of an element's content using JS. Note that the height of the element needs to be set to something smaller than the height taken by the content, otherwise this won't work.

\noindent\url{\ftjs scroll1.php}

\pagebreak

{\scriptsize\inputminted[tabsize=2, linenos=true]{html+php}{JS/scroll1.php}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a page with an image and 2 buttons. Pressing the first button sets the first image, pressing the second button sets the second image.
\end{Exercise}


\subsubsection{using \texttt{getAttribute} and \texttt{setAttribute}}
Instead of using element properties, we can use two HTMLElement methods, one to get and one to set the value of an attribute. Note that attribute values are treated as strings, i.e. \verb|getAttribute| always returns and \verb|setAttribute| takes a string. The attribute names used are the standard HTML ones, not the camel case versions used with element properties. These methods can also be used with non standard attributes as well as attributes of XML documents.

\noindent\url{\ftjs DOM_attributes2.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/DOM_attributes2.html}}

\subsubsection{using dataset attributes}
On occasion we might want to add our own attributes to HTML elements in order to store specific information. In order to be HTML5-compliant, we need to prefix our attribute names with "data-". Our attribute names may not contain capital letters A to Z or semicolons and may not start with "xml" (cf. \url{https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#attr-data-*}). A nice example can be found at \url{http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_global_data}. We can access dataset attributes using methods or using the \verb|dataset| property. In the latter case, attribute names are mapped to camel case property names. See also \url{https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset}.

\noindent\url{\ftjs DOM_attributes3.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/DOM_attributes3.html}}

\subsubsection{as \texttt{Attr} objects}
From p. 378 of the 6th edition of "JavaScript The Definitive Guide": The \verb|Node| type defines an \verb|attributes| property. This property is \verb|null| for any nodes that are not \verb|Element| objects. For \verb|Element| objects, \verb|attributes| is a read-only array-like object that represents all the attributes of the element." The \verb|Attr| object has \verb|name| and \verb|value| properties representing the name and value of the attribute.

\noindent\url{\ftjs DOM_attributes4.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/DOM_attributes4.html}}

\subsubsection{Manipulating an element's classes}
\verb|element.classList| is a highly useful property to manipulate an element's classes. See \url{https://developer.mozilla.org/en-US/docs/Web/API/Element/classList} for the details.

\subsection{Element content}
We can view the content of an element as HTML or plain text.

\subsubsection{as HTML}
The \verb|innerHTML| property of an \verb|Element| object contains the content as an HTML string. \verb|outerHTML| contains the content, including the opening and closing tag of the element. With \verb|insertAdjacentHTML| we can insert HTML before or after the beginning or before or after the end of a given element (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML}).

\begin{mdframed}[linecolor=red, linewidth=3pt, leftmargin=1cm, rightmargin=1cm]
\begin{quote}
insertAdjacentHTML() parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. \textbf{It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element.} This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation.
\end{quote}
\end{mdframed}

\noindent\url{\ftjs contentHTML.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/contentHTML.html}}

\subsubsection{as plain text}
The \verb|textContent| property of an \verb|Element| object contains the content as plain text.

\noindent\url{\ftjs contentText.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/contentText.html}}

\subsection{Managing nodes}
We create a new element with \verb|createElement| and a new 
text node with \verb|createTextNode|. There are other creation methods available, as detailed in \url{https://developer.mozilla.org/en-US/docs/Web/API/Document}.

With \verb|appendChild| we add a node as the last child of the given node. With \verb|insertBefore| we insert the new node (first parameter) before a given node (second parameter). If the second parameter is \verb|null|, the method behaves like \verb|appendChild|.

\verb|removeChild| is invoked on the parent node and given the child node that is to be removed as parameter. \verb|replaceChild| is also invoked on the parent node. It takes the node to be removed as first and the node that replaces the removed one as second parameter.


\noindent\url{\ftjs manageNodes.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/manageNodes.html}}

\subsubsection{Document fragments}
From \url{https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment}: "DocumentFragments are DOM Nodes. They are never part of the main DOM tree. The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children.

Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Consequently, using document fragments often results in better performance."

Cf. \url{http://jsperf.com/createdocumentfragmentvscreateelement}.

\pagebreak
\subsection{Determining the dimensions of elements}
\url{https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements}

\subsection{Manipulating CSS}
\begin{longtabu}{|X|}
\hline
\everyrow{\tabucline[0.5pt]{-}}
\url{http://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript} \\
\url{http://www.w3schools.com/js/js_htmldom_css.asp} \\
\url{http://www.w3schools.com/jsref/dom_obj_style.asp} \\
\url{https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle} \\
\url{https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration} \\
\end{longtabu}
\vspace*{\baselineskip}

We can easily manipulate CSS via JavaScript, which opens up some interesting applications, for instance moving HTML objects or changing colors dynamically.

In order to access internal or external stylesheets, we can use \verb|document.stylesheets|, which gives us an array with all stylesheets used by the document.

\noindent\url{\ftjs DOM_CSS1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/DOM_CSS1.html}}

In order to access the inline styling of a particular element, we can use the \verb|style| attribute of that element. For instance, if we want to change the color of the second \verb|p| element in our document, we could write:

\begin{scriptsize}
\begin{minted}[tabsize=2, linenos=true]{js}
document.querySelectorAll('p')[1].style.color = "#F0F";
\end{minted}
\end{scriptsize}

\noindent\includegraphics{Gorilla1}

Let's look at a more dynamic example, where we move a gorilla:

\noindent\url{\ftjs DOM_CSS2.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/DOM_CSS2.html}}

\subsubsection{\texttt{getComputedStyle}}
\url{https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle}

\begin{quotation}
The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
\end{quotation}

This method is particularly useful if we want to query an element's CSS value that we have not set programmatically.

\noindent\url{\ftjs DOM_CSS3.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/DOM_CSS3.html}}

\begin{Exercise}[difficulty=2, name={JavaScript Exercise}, counter=excjs]
Simplify the previous example (\verb|DOM_CSS2.html|) by replacing the four functions \verb|moveLeft|, \verb|moveRight|, \verb|moveUp| and \verb|moveDown| with a single function \verb|move|.
\end{Exercise}

\begin{Exercise}[difficulty=2, name={JavaScript Exercise}, counter=excjs]
Add the possibility for the user to change the number of pixels that the gorilla moves when a button is clicked.
\end{Exercise}

\begin{Exercise}[difficulty=2, name={JavaScript Exercise}, counter=excjs]
Remove the buttons from the previous example and modify the script so that the gorilla can be moved with the cursor keys.
\end{Exercise}

\section{\label{BOM}Browser Object Model (BOM)}
\verb|window| is the global object put at our disposal by the browser. It is of central importance and described in detail in \url{https://developer.mozilla.org/en-US/docs/Web/API/Window}. In \ref{JSIO} we have already met some useful \verb|window| methods. 

\subsection{Timers}
We can measure time, accurate to one microsecond, using the \verb|Performance.now| method (cf.
\url{https://developer.mozilla.org/en-US/docs/Web/API/Performance.now()}).

We can choose between three timer methods.

\subsubsection{\texttt{setTimeout}}
\verb|setTimeout| runs a given function (first parameter) after a specified number of milliseconds (second parameter) and returns the ID of the timeout, which can be used with \verb|clearTimeout| if we change our mind and do not want the timer to execute. \verb|setTimeout| is ideal if we just want to execute a function once after a given delay, as in the following example. Note that we need to use an anonymous function if we want to pass parameters to the function that is to be called by the timer:

\noindent\url{\ftjs setTimeout1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/setTimeout1.html}}

We can, however, also repeat the function call by invoking \verb|setTimeout| within the function that is to be executed repeatedly:
 
\noindent\url{\ftjs setTimeout2.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/setTimeout2.html}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create an HTML page with a button. If the user clicks the button, he will be automatically transferred to \url{http://wsers.foxi.lu} after 2 seconds.
\end{Exercise}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create an empty HTML page. After 1 second the page background color changes to red, then after 4 seconds it changes to green. 
\end{Exercise}

\begin{Exercise}[difficulty=2, name={JavaScript Exercise}, counter=excjs]
Create an HTML page with a button. After 1 second the page background color changes to red, then after 1 second it changes to green, after another second it changes back to red, then back to green etc. When the button is clicked, the background color does not change anymore.
\end{Exercise}

\subsubsection{\texttt{setInterval}}
\verb|setInterval| is identical to \verb|setTimeout| except that the given function gets invoked repeatedly until \verb|clearInterval| is called with the timer ID.
 
\noindent\url{\ftjs setInterval.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/setInterval.html}}

\noindent\includegraphics[width=\linewidth]{RadialGradiantAnim1}

This is an example of how we can create a background color animation using DOM CSS manipulation inside a timer function.

\noindent\url{\ftjs gradient_anim1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/gradient_anim1.html}}

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Repeat the previous exercise using \verb|setInterval| instead of \verb|setTimeout|.
\end{Exercise}

\subsubsection{\texttt{requestAnimationFrame}}
\begin{quotation}
You should call this method whenever you're ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation. The callback rate may be reduced to a lower rate when running in background tabs.
\end{quotation}
\begin{longtabu}{|X|}
\hline
\everyrow{\tabucline[0.5pt]{-}}
\url{https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame} \\
\url{http://www.w3.org/TR/animation-timing/\#requestAnimationFrame} \\
\end{longtabu}
\vspace*{\baselineskip}

\noindent\includegraphics{requestAnimationFrame1}

\noindent\url{\ftjs requestAnimationFrame1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/requestAnimationFrame1.html}}

\begin{Exercise}[difficulty=2, name={JavaScript Exercise}, counter=excjs]
Create a document with an image and use \verb|requestAnimationFrame| to implement a simple animation of your choice.
\end{Exercise}


\subsection{The \texttt{location} object}
This object allows us to redirect the browser to another page. See \url{http://www.w3schools.com/jsref/obj_location.asp} and \url{https://developer.mozilla.org/en-US/docs/Web/API/Window.location}.

\subsection{The \texttt{navigator} object}
See \url{http://www.w3schools.com/jsref/obj_navigator.asp} and \url{https://developer.mozilla.org/en-US/docs/Web/API/Navigator}.

\subsection{The \texttt{history} object}
See \url{http://www.w3schools.com/jsref/obj_history.asp} and \url{https://developer.mozilla.org/en-US/docs/Web/API/History}.

\subsection{The \texttt{screen} object}
See \url{http://www.w3schools.com/jsref/obj_screen.asp} and \url{https://developer.mozilla.org/en-US/docs/Web/API/Window.screen}.

\section{\index{strict mode}\label{strict mode}Strict mode}
\sloppypar The strict mode, according to ECMA, "provides enhanced error checking and program security". To enter this mode just put \texttt{"use strict";} at the top of any script. See \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode}.

To find out whether we are currently in strict mode, we can use this one liner from page 167 of the 6th edition of "JavaScript The Definitive Guide":
\begin{minted}{js}
var strict = (function() { return !this; } ());
\end{minted}

This works because in non-strict mode, the invocation context of a function is the global object, therefore \verb|!this| will be false. In strict mode, the invocation context is \verb|undefined|, thus \verb|!this| will be true.

In Firefox, you can set strict mode to default by changing \verb|javascript.options.strict| to \verb|true| in \verb|about:config|.

\section{Dates}
\begin{longtabu}{|X|}
\hline
\everyrow{\tabucline[0.5pt]{-}}
\url{http://www.htmlgoodies.com/html5/javascript/date-parsing-using-javascript-and-regular-expressions.html}\\
\url{http://stackoverflow.com/questions/6525538/convert-utc-date-time-to-local-date-time-using-javascript}\\
\end{longtabu}
\vspace*{\baselineskip}

\section{Viewports}
\begin{longtabu}{|X|}
\hline
\everyrow{\tabucline[0.5pt]{-}}
\url{http://www.quirksmode.org/mobile/viewports.html}\\
\url{http://www.javascriptkit.com/dhtmltutors/cssmediaqueries4.shtml}\\
\end{longtabu}
\vspace*{\baselineskip}

\section{AJAX}
From \url{https://developer.mozilla.org/en-US/docs/Glossary/AJAX}: \begin{quote}Asynchronous JavaScript And XML (AJAX) is a term used to describe the programming practice of using HTML, CSS, JavaScript, the Document Object Model (DOM), and the XMLHttpRequest object together to build complex Web pages that update their content without reloading the entire Web page. This makes the application faster and more responsive to user actions.\end{quote}

Study the gentle introduction to AJAX at \url{http://www.w3schools.com/ajax/default.asp}.

\subsection{\texttt{XMLHttpRequest}}
The key object that enables AJAX is \verb|XMLHttpRequest| (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest}), which allows us to take control of HTTP communication with a server, whereas normally this is handled in the background by the browser.

The required steps are the following:
\begin{enumerate}
\item Create an \verb|XMLHttpRequest| object.
\item Prepare the request using \verb|open| and register the event handler to handle the response.
\item Send the request to the server using \verb|send|.
\item When the server sends a response, an event gets triggered and our event handler reads the data and takes the required action, for instance update some parts of our web without a page reload.
\end{enumerate}

It's as easy as this:

\noindent\includegraphics{AJAX1}

\noindent\url{\ftajax AJAX1.html} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/AJAX/AJAX1.html}}
\noindent\ftajax AJAX1.php \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/AJAX/AJAX1.php}}

\subsubsection{\texttt{open(method, url, async, user, password)}}
For our purposes the relevant methods are \verb|POST| and \verb|GET| (cf. \ref{HTMLForms}). The second parameter represents the location of the server script that will receive the request. The third parameter is optional and \verb|true| by default, which specifies an asynchronous request, i.e. our script will not block to wait for the response. Instead, when the server sends a response, an event will be triggered to which our script can react. If this parameter is set to \verb|false|, our script will block and wait for the server response. Parameters four and five are only needed to access password protected resources.

\subsubsection{\texttt{send(data)}}
\verb|send| sends the request to the server. Any data that we want to send is given as argument. The following types can be used: \verb|ArrayBuffer|, \verb|ArrayBufferView|, \verb|Blob|, \verb|Document|, \verb|DOMString| and \verb|FormData|. To send binary data we should use \verb|Blob| (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/Blob}) or \verb|ArrayBufferView| (cf. \url{https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray}) objects.

The \verb|FormData| object (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/FormData}) allows us to programmatically send form data to the server just like the user can when sending an HTML form. To  use it we simply create a new \verb|FormData| object and then add name/value pairs to it using the \verb|append(name, value)| method. The \verb|name| parameter is a string whereas the \verb|value| parameter can be a string or a \verb|Blob| or a \verb|File|. In the latter two cases, a third optional parameter specifies the filename to be reported to the server. For \verb|Blob| objects the default filename is "blob". We can also use \verb|FormData| to submit an HTML form asynchronously (cf. \url{https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects}).

\subsubsection{\texttt{abort}}
This method aborts the request if it has already been sent.

\subsubsection{Events}
The following events are relevant for the \verb|XMLHttpRequest| object:
\begin{tabu}{|l|l|}
\hline
\texttt{loadstart} & triggered on request start \\
\hline
\texttt{progress} & triggered periodically during request execution \\
\hline
\texttt{abort} & triggered on request abortion \\
\hline
\texttt{error} & triggered if a request error occurs \\
\hline
\texttt{load} & triggered on successful request completion \\
\hline
\texttt{timeout} & triggered on request timeout \\
\hline
\texttt{loadend} & triggered after \texttt{load}, \texttt{abort} or \texttt{error} have been dispatched \\
\hline
\end{tabu}
\vspace*{\baselineskip}

We need to register a handler that takes care of the \verb|load| event. As we have seen in \ref{Events}, all event handlers automatically receive an \verb|Event| object when invoked. The \verb|target| attribute of the event corresponds to our \verb|XMLHttpRequest| object, given that we registered the event handler on this object. The \verb|status| attribute contains the HTTP response code (cf. \url{https://developer.mozilla.org/en-US/docs/Web/HTTP/Response_codes}) and \verb|statusText| the status in text form. If this code has the value 200, the request has succeeded and we can use the response data. A specific response header can be queried using \verb|getResponseHeader(header)| or we can retrieve a string with all response headers using \verb|getAllResponseHeaders|. Note that cookie headers are automatically filtered out. The \verb|XMLHttpRequest| object has three properties to contain the response data. \verb|response| contains the response in the format specified by the \verb|responseType| property. \verb|responseText| has the response in text format and \verb|responseXML| as a \verb|Document| object in parsed XML format, which can then be traversed as described in \ref{DOMTraversal}, if applicable.

\begin{Exercise}[difficulty=1, name={JavaScript Exercise}, counter=excjs]
Create a valid HTML5 page that contains an image. If the user clicks on the image, a PHP script is executed that sends additional HTML code, which is inserted after the image in the current document.
\end{Exercise}

\vspace*{\baselineskip}
Let's look at a couple more examples:

\noindent\includegraphics{AJAX2}

\noindent\url{\ftajax AJAX2.html} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/AJAX/AJAX2.html}}
\noindent\ftajax AJAX2.php \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/AJAX/AJAX2.php}}

\noindent\includegraphics[width=\linewidth]{AJAX3}

\noindent\url{\ftajax AJAX3.html} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/AJAX/AJAX3.html}}

We can easily use AJAX to upload files to a server. If we want to monitor the upload progress, all we need to do is assign an event handler to the \verb|upload| property of our \verb|XMLHttpRequest|. This handler will automatically receive a \verb|ProgressEvent| (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent}) object as argument. Using the three properties \verb|lengthComputable|, \verb|loaded| and \verb|total| we can monitor the upload progress.

\noindent\url{\ftajax AJAX4.html} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/AJAX/AJAX4.html}}
\noindent\ftajax AJAX4.php \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/AJAX/AJAX4.php}}

\subsubsection{\texttt{setRequestHeader(header, value)}}
In some cases we need to specify specific HTTP headers to give the server additional information with regards to the data we want to send and/or receive. \verb|setRequestHeader| sets the value of the HTTP request header. If used, \textbf{it must be called after \texttt{open} but before \texttt{send}}. If this method is called several times with the same header, the values are merged into one single request header. The official header list can be found at \url{http://www.iana.org/assignments/message-headers/message-headers.xml#perm-headers} and the official value list for the "Content-Encoding" header, which is the most often used one for our purposes, can be found at \url{http://www.iana.org/assignments/media-types/media-types.xhtml}.

\subsection{\label{COR}Cross-origin requests}
According to \url{https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy}:
\begin{quote}
The same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin.
\end{quote}
Cross-Origin Resource Sharing (CORS) is one way to get around these restrictions. The details can be found at  \url{https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS}

In its simplest form, to give everyone access, we can just add the following at the top of our PHP script:
\begin{scriptsize}
\begin{minted}{php}
header('Access-Control-Allow-Origin: *');
\end{minted}
\end{scriptsize}

Another possibility is to use JSONP (JSON with padding) as explained in \url{https://en.wikipedia.org/wiki/JSONP}. For a practical application example, study \ref{WMOTUInvaders}.

\section{JSON}
JavaScript Object Notation (JSON) is a data serialization format often used to exchange data, including complex objects, between server and client. Objects are converted into a JSON string, which is sent to/from the server from/to the client.

JSON is based on a subset of JavaScript (cf. \url{http://json.org}, \url{http://www.w3schools.com/json/default.asp} and \url{http://en.wikipedia.org/wiki/JSON}). Data consists of name/value pairs separated by commas and embedded within \verb|{}|. \verb|[]| are used for arrays. \textbf{Note that key names and strings need to be enclosed in double quotes.} Use \url{http://jsonlint.com} to verify that a given string is valid JSON.

In JavaScript, we use \verb|JSON.stringify| to encode and \verb|JSON.parse| to decode a JSON string.

You can play around with JSON at \url{http://www.tutorialspoint.com/online_json_editor.htm}.

Example:
\begin{scriptsize}
\begin{minted}{js}
// Create basic JS object.
var myObj = {firstName: "Donald", lastName: "Duck"};
// Convert JS object to JSON string: '{"firstName":"Donald","lastName":"Duck"}'
console.log(JSON.stringify(myObj));
// -> Convert string back to JS object: {firstName: "Donald", lastName: "Duck"}
JSON.parse(JSON.stringify(myObj));
\end{minted}
\end{scriptsize}

In PHP, we use \verb|json_encode| and \verb|json_decode| respectively.

\noindent\url{\ftjson JSON1.html} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/JSON/JSON1.html}}
\noindent\ftjson JSON1.php \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/JSON/JSON1.php}}

\noindent\url{\ftjson JSON2.html} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/JSON/JSON2.html}}
\noindent\ftjson JSON2a.php \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/JSON/JSON2a.php}}
\noindent\ftjson JSON2b.php \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/JSON/JSON2b.php}}

Here is a simple example of reading JSON data from a text file and displaying it in an HTML table:

\noindent\url{\ftjson cars.json} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/JSON/cars.json}}
\noindent\url{\ftjson JSON3.html} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/JSON/JSON3.html}}

Here is an example of exchanging more complex objects between client and server:

\noindent\url{\ftjson JSON4.html} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/JSON/JSON4.html}}
\noindent\ftjson JSON4.php \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/JSON/JSON4.php}}

\section{Application Programming Interfaces (API)}
To find out which HTML5 APIs your browser supports, use \url{https://html5test.com}.

\subsection{File}
The File API allows our app to represent and access file objects.
\begin{longtabu}{|X|}
\hline
\everyrow{\tabucline[0.5pt]{-}}
\url{http://www.w3.org/TR/FileAPI}\\
\url{http://www.html5rocks.com/en/tutorials/file/dndfiles}\\
\url{http://www.codeproject.com/Articles/668351/HTML-File-API-Capability-and-Compatibility}\\
\end{longtabu}
\vspace*{\baselineskip}

\url{\ftjs file1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/file1.html}}

\subsection{\label{DrandAndDrop}Drag and drop}
To make any object drag and droppable it needs to have its \texttt{position} attribute set to \texttt{absolute} or \texttt{fixed}. We can then use Peter-Paul Koch's \texttt{dragDrop} object (cf. \url{http://www.quirksmode.org/js/dragdrop.html}), which does not use the drag and drop API but implements a solution based on the classic \texttt{mousemove} and \texttt{mouseup} events. It works very well across browsers. A stripped-down version is used in the following example:

\url{\ftjs draganddrop1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/draganddrop1.html}}

The following two examples show a Window class to create a draggable and resizable window:

\noindent\includegraphics{window1}

\url{\ftjs window1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/window1.html}}

\url{\ftjs window1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/window1.js}}

\noindent\includegraphics{window2}

\url{\ftjs window2.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/window2.html}}

\url{\ftjs window2.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/window2.js}}

If we want to use the HTML5 drag and drop API instead of this object, we need to set the \texttt{draggable} attribute to \texttt{true}.
See \url{https://developer.mozilla.org/en-US/docs/DragDrop/Drag_and_Drop} and \url{http://developers.whatwg.org/dnd.html#dnd} for an in-depth explanation of drag and drop.

\subsection{Web Workers}
Warning: this script will use 100\% of the processing power of a 4 core CPU.
\noindent\url{\ftwebworkers demo1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/WebWorkers/demo1.html}}

\subsection{Server-Sent Events}
This API allows the opening  of an HTTP connection for receiving push notifications from a server in the form of DOM events. The specification can be found at \url{http://www.w3.org/TR/2009/WD-eventsource-20091029}. Good descriptions and examples can be found at:
\begin{longtabu}{|X|}
\hline
\everyrow{\tabucline[0.5pt]{-}}
\url{http://www.html5rocks.com/en/tutorials/eventsource/basics} \\
\url{http://html5doctor.com/server-sent-events} \\
\url{http://www.sitepoint.com/server-sent-events} \\
\url{https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events} \\
\url{http://chimera.labs.oreilly.com/books/1230000000545/ch16.html} \\
\url{https://html.spec.whatwg.org/multipage/comms.html\#server-sent-events} \\
\end{longtabu}
\vspace*{\baselineskip}

Here is a simple example that sends the current server time to the client every second. Take a look at the networking tab of the browser console. The communication takes place without new HTTP requests, as the existing one is kept alive. This is more efficient than using AJAX polling on the client side, i.e. each client checking with the server every second to see whether any new data has arrived.
\textbf{When using sessions, we must call \texttt{session\_write\_close}, otherwise the session object will be locked and no other script can use it, given that our SSE-server runs an endless loop.}

\noindent\url{\ftsse SSE_client.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/ServerSentEvents/SSE_client.html}}
\noindent\ftsse SSE\_server.php
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/ServerSentEvents/SSE_server.php}}

Here is a monitoring app that pushes the last 30 lines of the PHP error log to all clients every second:

\noindent\url{\ftsse log_monitor_client.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/ServerSentEvents/log_monitor_client.html}}
\noindent\ftsse log\_monitor\_server.php
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/ServerSentEvents/log_monitor_server.php}}

Nicolas Detombes has developed a chat app that nicely illustrates how SSE can be used:

\noindent\url{\ftsse chat\_client.php}
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/ServerSentEvents/chat_client.php}}
\noindent\ftsse chat\_comment.php
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/ServerSentEvents/chat_comment.php}}
\noindent\ftsse chat\_database.php
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/ServerSentEvents/chat_database.php}}
\noindent\ftsse chat\_load.php
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/ServerSentEvents/chat_load.php}}

\subsection{Canvas}
Study the excellent documentation at 
\url{https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial} and \url{http://www.w3schools.com/html/html5_canvas.asp}. A good reference can be found at \url{http://www.w3schools.com/tags/ref_canvas.asp}.

Here is a pacman trying to catch the mouse cursor:

\noindent\url{\ftcanvas pacman.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Canvas/pacman.html}}

Here is a skeleton for a pong game:

\noindent\url{\ftcanvas pong.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Canvas/pong.html}}

\noindent\url{\ftcanvas pong.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{js}{JS/Canvas/pong.js}}

And here is a random maze generator class:

\noindent\url{\ftcanvas maze1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Canvas/maze1.html}}

\subsection{Web Sockets}
So far we've used HTTP POST or GET requests to send data to the server, who responded with new HTML. This is a very inefficient and limited approach. If we want real-time two way communication between the server and a potentially large number of clients, we should take advantage of the new \href{https://developer.mozilla.org/en-US/docs/Web/API/WebSocket?redirectlocale=en-US\&redirectslug=WebSockets\%2FWebSockets\_reference\%2FWebSocket}{JavaScript WebSocket API} that is available in Firefox and Chrome. By establishing a bidirectional communication channel between the server and each client, we can for instance implement real-time chat.

The easiest way to get started can be found at \url{http://websocketd.com}.

\subsubsection{Client}
On the client side, we need to implement the following:
\begin{scriptsize}
\begin{minted}[tabsize=2, linenos=true]{javascript}
var socket = new
  WebSocket("ws://foxi.ltam.lu:35000");
socket.addEventListener('open', opened);
socket.addEventListener('message', received);
socket.addEventListener('close', closed);
socket.addEventListener('error', error);

function opened() {

}

function received(event) {
	console.log("Received: ", event.data);
}

function closed() {

}

function error(event) {
	console.error("Error: ", event.data);
}

function send(event) {
	socket.send("Hello world!");
}
\end{minted}
\end{scriptsize}
\texttt{opened} will be called once the web socket connection is ready.
\texttt{received} will be called when a message from the server has been received.

\subsubsection{Server}
Currently the Apache web server does not come with a web socket module. We could write our own web socket server in PHP, but why reinvent the wheel when there are good open source libraries available. We'll use \url{https://github.com/Devristo/phpws} and adapt it to our needs.
Download the zip file and extract it on the web server. If you are interested in the implementation details, take a look at the files. For our purposes, we only need to modify the \texttt{demo.php} file, particularly the \texttt{onMessage} function. Make a copy of the file and save it as \texttt{server.php}.

Here is a sample implementation of \texttt{onMessage}, which simply sends the message received to all other clients:
\begin{scriptsize}
\begin{minted}[tabsize=2, linenos=true, startinline=true]{php5}
public function onMessage(IWebSocketConnection $user, IWebSocketMessage $msg) {
	$thisuser = $user->getId();
	$msg      = trim($msg->getData());
	$msgback  = WebSocketMessage::create($msg);

	foreach ($this->server->getConnections() as $user)
		if ($user->getId() !== $thisuser) $user->sendMessage($msgback);
}
\end{minted}
\end{scriptsize}

\subsection{\label{WebGL}WebGL}
\begin{quotation}
WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D graphics and 2D graphics within any compatible web browser without the use of plug-ins
\end{quotation} (cf. \url{https://developer.mozilla.org/en-US/docs/Web/WebGL}).

Relevant web pages:
\begin{longtabu}{|X|}
\hline
\everyrow{\tabucline[0.5pt]{-}}
\url{https://www.khronos.org/registry/webgl/specs/1.0} \\
\url{https://www.khronos.org/webgl/wiki/Main_Page} \\
\url{https://developer.cdn.mozilla.net/media/uploads/demos/a/z/azakai/3baf4ad7e600cbda06ec46efec5ec3b8/bananabread_1373485124_demo_package/index.html} \\
\url{https://www.urbangalaxyonline.com} \\
\url{http://www.spacejack.ca/spacejack} \\
\url{http://hexgl.bkcore.com/play} \\
\url{http://htmlchess.sourceforge.net/demo/example.html} \\
\url{http://www.chromeexperiments.com/webgl} \\
\url{http://playwebgl.com} \\
\end{longtabu}

WebGL 2 will be even better, cf. \url{https://www.youtube.com/watch?v=2v6iLpY7j5M}.

\subsubsection{Three.js}
Given the complexity of direct WebGL programming, we'll start by using the \verb|Three.js| JavaScript library, which can be downloaded from \url{https://github.com/mrdoob/three.js} and greatly simplifies the development of 3D web apps.

The best way to get started is to study the documentation at \url{http://threejs.org/docs/#Manual/Introduction/Creating_a_scene} and \url{http://threejsdoc.appspot.com/doc/index.html}.

Let's start with a very simple example and walk it through step by step:

\noindent\includegraphics[width=\linewidth]{Threejs1}

\noindent\url{\ftwebgl Three.js/test1.html}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{html}{JS/WebGL/Three.js/test1.html}} 

As explained in the Three.js introductory example, we need a scene, a camera and a renderer to display the scene using the camera. The renderer needs the canvas element, which is where the whole scene will be displayed.

Our script consists of 3 functions:
\begin{enumerate}
\item An initialization function that creates the scene, the camera and the renderer. It then adds them to the DOM and starts the rendering. This function is executed only once, after the document has been loaded.
\item The rendering function, which calls itself using \verb|requestAnimationFrame| (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame}). Here we perform the animation, but only if the animation is supposed to be running as indicated by the boolean global variable. In this simple example we rotate our cube around the x and y axes.
\item \verb|toggleAnimation| simply toggles a boolean global variable, which indicates whether the animation is currently meant to be running or stopped. In the former case, the render function gets executed. \\
\end{enumerate}

Here's a slightly more evolved example:

\noindent\includegraphics[width=\linewidth]{Threejs2}

\noindent\url{\ftwebgl Three.js/test2.html}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{html}{JS/WebGL/Three.js/test2.html}} 

Instead of declaring a canvas element, we'll let the renderer take care of that. We'll let the scene take up the whole browser window width and height. We can even switch to full screen mode using \verb|F11|. Finally we use Mr. Doob's performance monitor, available from \url{https://github.com/mrdoob/stats.js}.

As a further evolutionary step, we can add user controls (cf. \url{https://code.google.com/p/dat-gui}), mouse interaction and a funny background plane:

\noindent\includegraphics[width=\linewidth]{cover4}

\noindent\url{\ftwebgl Three.js/3js1.html}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{html}{JS/WebGL/Three.js/3js1.html}} 

\paragraph{Loading a Collada model} ~\\

\noindent\includegraphics[width=\linewidth]{threejscollada1}

\noindent\url{\ftwebgl Three.js/load_collada.html}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{html}{JS/WebGL/Three.js/load_collada.html}} 


\paragraph{Physijs}

\noindent\url{https://github.com/chandlerprall/Physijs}

\paragraph{FPS}

Let's have some real fun and create a first person shooter (FPS) from scratch.

\noindent\includegraphics[width=\linewidth]{threejs3}

\noindent\url{\ftwebgl Three.js/FPS/index.html}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{html}{JS/WebGL/Three.js/FPS/index.html}} 

\noindent\url{\ftwebgl Three.js/FPS/main.js}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{js}{JS/WebGL/Three.js/FPS/main.js}} 

\url{http://carvisualizer.plus360degrees.com/threejs}

\url{http://hexgl.bkcore.com}

\url{http://portableapps.com/apps/graphics_pictures/blender_portable}

\url{https://github.com/tparisi/Vizi}

\url{http://www.peter-strohm.de/webgl/index.php}
\url{http://www.khronos.org/webgl/wiki/User_Contributions}

\subsubsection{GLAM}
GLAM (GL And Markup) is a declarative language for 3D web content (cf. \url{http://tparisi.github.io/glam}).

\subsubsection{Cesium}
This is a JavaScript library for creating 3D globes and 2D maps (cf. \url{http://cesiumjs.org}).

\noindent\includegraphics[width=\linewidth]{Cesium1}
\noindent\url{\ftwebgl Cesium/cesium1.html}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{html}{JS/WebGL/Cesium/cesium1.html}} 

\subsubsection{Direct WebGL programming}
All WebGL drawing happens inside the HTML canvas element (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement.getContext}). Before using the WebGL API we need a \verb|WebGLRenderingContext| object (cf. \url{https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext}), which manages the whole 3D drawing process. To get it we call the \verb|getContext| method of the canvas element and pass \verb|webgl| as parameter to get the 3D context. If we pass \verb|2d| we get a 2D context. If we wanted to ensure compatibility with older browsers, we would have to check  \verb|experimental-webgl|, \verb|webkit-3d| and \verb|moz-webgl| as parameters to get a 3D context, but we will assume that the user uses an up to date browser. \\

WebGL methods correspond to OpenGL methods documented at \url{https://www.khronos.org/opengles/sdk/docs/man}. \\

Useful \verb|WebGLRenderingContext| methods:
\begin{itemize}
\item \verb|createShader(type)| creates an empty shader object of the given type (\verb|VERTEX_SHADER| or \verb|FRAGMENT_SHADER|) and returns it's reference.
\item \verb|createProgram()| creates an empty program object and returns it's reference. 
\item \verb|clearColor(red, green, blue, alpha)| sets color for drawing area. Values from 0 to 1, alpha === 1 -> opaque, alpha === 0 -> fully transparent.
\item \verb|shaderSource(shader, source)| replaces the source code in a shader object.
\item \verb|compileShader(shader)| compiles the shader object.
\item \verb|attachShader(program, shader)| attaches a shader to a program.
\item \verb|linkProgram(program)| links a program.
\item \verb|useProgram(program)| installs the program as part of the current rendering state.
\item \verb|clearColor(red, green, blue, alpha)| specifies clear values for the color buffers.
\item \verb|clear(buffer)| clears the buffer(s) specified. It takes a single argument. If several buffers are to be cleared it is the bitwise OR of several values from \verb|GL_COLOR_BUFFER_BIT|, \verb|GL_DEPTH_BUFFER_BIT| and \verb|GL_STENCIL_BUFFER_BIT|.
\item \verb|drawArrays(mode, first, count)| renders primitives from array data. The first parameter specifies what kind of primitives to render. Choices are \verb|GL_POINTS|, \verb|GL_LINE_STRIP|,
\verb|GL_LINE_LOOP|, \verb|GL_LINES|, \verb|GL_TRIANGLE_STRIP|, \verb|GL_TRIANGLE_FAN| and
\verb|GL_TRIANGLES|.
\item \verb|getAttribLocation(program, name)| returns the location of an attribute variable.
\item \verb|vertexAttrib3f(index, v0, v1, c2)| specifies the value of a generic vertex attribute. Similar methods end with \verb|1f|, \verb|2f| or \verb|4f|. From \url{https://www.khronos.org/opengles/sdk/docs/man}: \begin{quote}
These commands can be used to specify one, two, three, or	all four components of the generic vertex attribute specified by index. A 1 in the name of the command indicates that only one value is passed, and it will be used to modify the first component of the generic vertex attribute. The second and third components will be set to 0, and the fourth component will be set to 1. Similarly, a 2 in the name of the command indicates that	values are provided for the first two components, the third component will be set to 0, and the fourth component will be set to 1. A 3 in the name of the command indicates that values are provided for the first three components and the fourth component will be set to 1, whereas a 4 in the name indicates that values are provided for all four components.
\end{quote}
\item \verb|getUniformLocation(program, name)| returns the location of a uniform variable.
\item \verb|uniform[1, 2, 3, 4]f(index, v0 [, v1, v2, v3])| specifies the values of a uniform variable.
\item \verb|createBuffer()| creates a buffer object.
\item \verb|deleteBuffer(buffer)| deletes a buffer object.
\item \verb|bindBuffer(target, buffer)| binds a buffer object telling WebGL what type of data it contains. \verb|target| must be \verb|GL_ARRAY_BUFFER| or \verb|GL_ELEMENT_ARRAY_BUFFER|.
\item \verb|bufferData(target, data, usage)| creates and initializes a buffer object's data store. \verb|target| must be \verb|GL_ARRAY_BUFFER| or \verb|GL_ELEMENT_ARRAY_BUFFER|. \verb|usage| is one of \verb|GL_STREAM_DRAW|, \verb|GL_STATIC_DRAW|, or \verb|GL_DYNAMIC_DRAW|.
\item \verb|vertexAttribPointer(location, size, type, normalized, stride, offset)|
\end{itemize}

WebGL uses typed arrays for maximum performance:
\begin{longtabu}{|l|l|}
\hline
\everyrow{\tabucline[0.5pt]{-}}
\textbf{Array} & {Bytes} \\
\texttt{Int8Array} & 1 \\
\texttt{Uint8Array} & 1 \\
\texttt{Int16Array} & 2 \\
\texttt{Uint16Array} & 2 \\
\texttt{Int32Array} & 4 \\
\texttt{Uint32Array} & 4 \\
\texttt{Float32Array} & 4 \\
\texttt{Float64Array} & 8 \\
\end{longtabu}
\vspace*{\baselineskip}

To create a typed array, we call the constructor.

Typed arrays have the following methods, properties and constants:
\begin{longtabu}{|l|}
\hline
\everyrow{\tabucline[0.5pt]{-}}
\texttt{get(index)} \\
\texttt{set(index, value)} \\
\texttt{set(array, offset)} \\
\texttt{length} \\
\texttt{BYTES\_PER\_ELEMENT} \\
\end{longtabu}
\vspace*{\baselineskip}

Let's look at two simple examples:

\noindent\includegraphics[width=\linewidth]{WebGLdirect1}

\noindent\url{\ftwebgl Direct/webgl1.html}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{html}{JS/WebGL/Direct/webgl1.html}} 

\noindent\url{\ftwebgl Direct/vertex_shader1.js}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{js}{JS/WebGL/Direct/vertex_shader1.js}} 

\noindent\url{\ftwebgl Direct/fragment_shader1.js}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{js}{JS/WebGL/Direct/fragment_shader1.js}} 

\noindent\includegraphics[width=\linewidth]{WebGLdirect2}

\noindent\url{\ftwebgl Direct/webgl2.html}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{html}{JS/WebGL/Direct/webgl2.html}} 

\noindent\url{\ftwebgl Direct/vertex_shader2.js}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{js}{JS/WebGL/Direct/vertex_shader2.js}} 

\noindent\url{\ftwebgl Direct/fragment_shader2.js}
{\scriptsize
\inputminted[tabsize=2, linenos=true]{js}{JS/WebGL/Direct/fragment_shader2.js}}

\subsubsection{Blender}
According to \url{http://www.blender.org}:
\begin{quote}
Blender is a free and open source 3D animation suite. It supports the entirety of the 3D pipeline—modeling, rigging, animation, simulation, rendering, compositing and motion tracking, even video editing and game creation.
\end{quote}

Blender is an extremely powerful application. Unfortunately, it's user interface is not necessarily the easiest one to master.

\subsection{Page Visibility}
"The Page Visibility specification defines a means for site developers to programmatically determine the current visibility of a document and be notified of visibility changes." cf. 
\url{http://www.w3.org/TR/2011/WD-page-visibility-20110602}.
This API is very useful for instance in the case of WMOTU Invaders, where we do not want the aliens to continue moving and shooting in the background whilst we are not playing the game! Take a look at \ref{WMOTUInvadersOO} to see how it's done. Further details and examples can be found at \url{https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API}.

\subsection{WebAudio}
Two excellent Web resources are \url{http://www.html5rocks.com/en/tutorials/webaudio/intro} and \url{http://webaudioapi.com}.

Here is a simple example:

\noindent\url{\ftjs webaudio1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/webaudio1.html}}
\noindent\url{\ftjs webaudio1.js}
{\scriptsize\inputminted[tabsize=2, linenos=true]{javascript}{JS/webaudio1.js}}

\subsection{Observers}
\subsubsection{MutationObserver}
\url{https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver?redirectlocale=en-US&redirectslug=DOM%2FMutationObserver}

\subsubsection{Web Storage}
Web Storage provides a larger, more secure, and easier-to-use alternative to storing information in cookies. The official specification is at \url{http://www.w3.org/TR/webstorage} and good introductions with examples can be found at \url{http://www.sitepoint.com/an-overview-of-the-web-storage-api}, \url{http://html5doctor.com/storing-data-the-simple-html5-way-and-a-few-tricks-you-might-not-have-known} and \url{https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage}.

\subsubsection{Object.observe}
\url{http://www.html5rocks.com/en/tutorials/es7/observe}

\subsection{Web Animations}
\url{http://w3c.github.io/web-animations}
\url{http://updates.html5rocks.com/2014/05/Web-Animations---element-animate-is-now-in-Chrome-36}

\subsection{Web Messaging}
\url{http://en.wikipedia.org/wiki/Web_Messaging}

\subsection{Service Manager}
\url{https://jakearchibald.github.io/isserviceworkerready/resources.html}

\url{http://www.html5rocks.com/en/tutorials/service-worker/introduction/}

\section{Tools}
\subsection{Minimizers, optimizers, obfuscators, deobfuscation, compressors and beautifiers}
Obfuscation means making the code unreadable for human beings whilst preserving its function. A short but insightful article on obfuscation can be found at \url{http://blog.qburst.com/2012/10/dont-tell-what-you-are-capable-of-javascript-obfuscation}. An excellent survey of obfuscation techniques can be found in \url{http://www.cse.psu.edu/~szhu/papers/malware.pdf}.
A good overview of minification resources can be found at \url{https://developers.google.com/speed/docs/insights/MinifyResources#overview}.

\subsubsection{JavaScript Obfuscator}
A good JS obfuscator can be found at \url{http://javascriptobfuscator.com/default.aspx}.

\subsubsection{Deobfuscation}
Obfuscated code that uses some form of encryption usually starts with \verb|eval| and can be deobfuscated by replacing \verb|eval| with for instance \verb|alert| or \verb|console.log|. Here is a simple deobfuscator for encrypted JavaScript:

\noindent\url{\ftjs decodeJS.html} \\
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/decodeJS.html}}

See also \url{http://www.r00tsec.com/2011/09/java-deobfuscate-trick-and-tools.html}

\subsubsection{Online JavaScript beautifier}
The best tool to beautify, unpack or deobfuscate JavaScript and HTML cn be found at \url{http://jsbeautifier.org}.

\subsubsection{Google Closure Compiler}
\begin{quotation}
The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls. 
\end{quotation} Be careful with the advanced mode, as it will often break your script. Careful testing of the compiled script is recommended.
(cf. \url{http://closure-compiler.appspot.com/home})

\subsubsection{Esmangle}
"esmangle is mangler / minifier for Mozilla Parser API AST." (cf. \url{http://constellation.github.io/esmangle})

\subsubsection{UglifyJS}
"UglifyJS is a JavaScript compressor/minifier written in JavaScript." (cf. \url{http://lisperator.net/uglifyjs})

\subsubsection{JavaScript Utility}
The tool at \url{http://jsutility.pjoneil.net} allows the testing, validating, formatting, obfuscating, compacting and compressing of JavaScript code.

\subsubsection{Dean Edwards Packer}
\url{http://dean.edwards.name/packer} allows to easily reduce the size of your script by shrinking variable names. Be careful with base 62 encoding, as it can easily break your script. Careful testing of the packed script is recommended.

\subsection{Editor components and online editors}
\subsubsection{JSFiddle}
\url{http://jsfiddle.net}

\subsubsection{CodeMirror}
"CodeMirror is a code-editor component that can be embedded in Web pages." (cf. \url{http://codemirror.net})
It is the component that I've used in the training section of \url{http://cliss.foxi.lu}.

\subsubsection{ACE}
"Ace is an embeddable code editor written in JavaScript." (cf. \url{http://ace.c9.io})

\subsubsection{Cloud-based editors}
\url{http://www.hongkiat.com/blog/cloud-ide-developers} provides a good overview of the rapidly evolving cloud IDE space.

\section{Game engines}
\subsection{Jaws}
\url{http://www.jawsjs.com}

\section{Frameworks}
\subsection{jQuery}
From \url{http://jquery.com}:
\begin{quote}
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
\end{quote}
The API documentation can be found at \url{http://api.jquery.com/}.

\subsubsection{Pros and cons}
For a description of the advantages offered by jQuery, have a look at \url{http://www.w3schools.com/jquery/jquery_intro.asp}. Drawbacks include the inclusion of additional code (jquery-2.1.1.min.js has a file size of 82 KB), the slower execution speed due to the additional compatibility and ease of use translations under the hood, the large amount of warnings that appear in the console and the need to learn another syntax. 

\subsubsection{Download}
jQuery is available in versions 1.x and 3.x, compressed and uncompressed. The difference between versions 1.x and 3.x is that the former support Internet Explorer going back to version 6, whereas Internet Explorer support in the latter only goes back to version 9 (cf. \url{http://jquery.com/browser-support}).

To use jQuery, we can download the version we want from the site or have our HTML document retrieve it from a content delivery network (CDN) at runtime, as explained at \url{http://jquery.com/download} with links for the different jQuery versions at \url{https://code.jquery.com}. Be careful to avoid "slim" versions, as they exclude AJAX and effects ()\url{https://blog.jquery.com/2016/06/09/jquery-3-0-final-released}). 

Let's look at these 2 options:
\begin{scriptsize}
\begin{minted}{html}
<script src=jquery-3.1.0.min.js></script>
<script src="//code.jquery.com/jquery-3.1.0.min.js"></script>
\end{minted}
\end{scriptsize}

\subsubsection{Selecting elements}
The basic principle of jQuery is to select some elements and then do something with them. For this purpose, we ca use the \verb|$(selector)| or \verb|jQuery(selector)| functions. These two are identical. The former one is used most often as it is shorter. It may however pose problems when we try to use several frameworks, with another framework also defining a global \verb|$(selector)| function. In this case, we can use \verb|jQuery(selector)| to avoid any conflicts.
The selector passed as parameter is a standard CSS selector (cf. \ref{CSSSelectors}). See \url{http://www.w3schools.com/jquery/jquery_selectors.asp} for examples. The resulting set of elements is a jQuery object, which is very easy to work with.

\subsubsection{Changing the DOM}
See the documentation starting with \url{http://www.w3schools.com/jquery/jquery_dom_get.asp}.

\subsubsection{DOM traversal}
\url{http://www.w3schools.com/jquery/jquery_ref_traversing.asp} provides a great overview of the numerous jQuery DOM traversal methods.

\subsubsection{Handling events}
See \url{http://www.w3schools.com/jquery/jquery_events.asp} and \url{http://www.w3schools.com/jquery/jquery_ref_events.asp}.

\subsubsection{AJAX}
\paragraph{\texttt{load}} ~\\
\verb|$(selector).load(URL [, data] [, callback])| is a very easy to use method to load data from the server directly into an HTML element (cf. \url{http://api.jquery.com/load}). 

\paragraph{\texttt{post}} ~\\
\verb|$.post(url [, data] [, success] [, dataType])| loads data from a server using a HTTP POST request (cf. \url{http://api.jquery.com/jQuery.post}).

\paragraph{\texttt{get}} ~\\
\verb|$.get(url [, data] [, success] [, dataType])| loads data from a server using a HTTP GET request (cf. \url{http://api.jquery.com/jQuery.get}).

\paragraph{\texttt{getJSON}} ~\\
\verb|$.getJSON(url [, data] [, success])| loads JSON-encoded data from a server using a GET HTTP request (cf. \url{http://api.jquery.com/jQuery.getJSON}).

\paragraph{\texttt{ajax}} ~\\
\url{http://api.jquery.com/jQuery.ajax}, \url{http://hayageek.com/jquery-ajax-form-submit}.

\paragraph{Differentiating between AJAX and standard form requests}
jQuery adds a \verb|X_Requested_With| header to every AJAX request. This allows our server script to detect whether data comes from an AJAX request or a standard form submission. To see the difference, you can run the test page \verb|jQAJAXTest.html|, analyze the server response and compare it with the AJAX response received in the main example \verb|jQAJAX1.html|:

\noindent\url{\ftjquery jQAJAX1.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/jQuery/jQAJAX1.html}}
\noindent\ftjquery jQAJAX1.php
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/jQuery/jQAJAX1.php}}
\noindent\url{\ftjquery jQAJAX1.json}
{\scriptsize\inputminted[tabsize=2, linenos=true]{json}{JS/jQuery/jQAJAX1.json}}
\noindent\url{\ftjquery jQAJAXTest.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/jQuery/jQAJAXTest.html}}

\noindent\url{\ftjquery jQAJAX2.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/jQuery/jQAJAX2.html}}
\noindent\ftjquery jQAJAX2.php
{\scriptsize\inputminted[tabsize=2, linenos=true]{php}{JS/jQuery/jQAJAX2.php}}

\subsubsection{Effects}
\url{http://www.w3schools.com/jquery/jquery_ref_effects.asp}

\subsection{Dojo}
\url{http://dojotoolkit.org}

\subsection{D3}
\url{http://d3js.org}

\subsection{Qooxdoo}
\url{http://qooxdoo.org}

\section{Libraries}
\subsection{Tables}
\subsubsection{DataTables}
\url{https://www.datatables.net}

\subsubsection{Editablegrid}
\url{http://www.editablegrid.net}

\section{JSDoc}
From \url{https://en.wikipedia.org/wiki/JSDoc}: "JSDoc is a markup language used to annotate JavaScript source code files."
JSDoc annotations are embedded within \verb|/**| and \verb|*/|. See the URL for details.

\section{Web Components}
\url{http://webcomponents.org}
\url{https://developer.mozilla.org/en-US/docs/Web/Web_Components}

\subsection{Custom elements}
\url{http://www.html5rocks.com/en/tutorials/webcomponents/customelements}

\subsection{HTML import}
\url{http://www.html5rocks.com/en/tutorials/webcomponents/imports}

\subsection{HTML templates}
\url{https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template}

\section{Problems}

\subsection{Show/hide HTML element}
\noindent\includegraphics{show_hide_element}

Write a page that displays an image and a button. Clicking on the button makes the image appear, clicking it again makes the image disappear.

\subsection{Color preview}
\noindent\includegraphics{color_preview}

Write an app that displays three sliders, one for {\color{red}red}, one for {\color{green}green} and one for {\color{blue}blue}. The body background color is always the color of the currently selected red, green and blue values, each one between 0 and 255. The current value of each slider is shown.

\subsection{Puzzle}
Write an app that randomly selects a picture from a directory and cuts it in a random number of pieces. It then shows a random piece to the user who has to place it on the right spot in the solution area. The user can rearrange the pieces of the solution area at any time.

\subsection{Path tracker}
The path tracker mobile app provides a start and a stop button. After the start button has been pressed, the app records the current position of the device every second and stores it. When the stop button is pressed, the user is shown a map with his itinerary and some statistical information, e.g. time taken, average speed, etc.

\subsection{Paint app}
Write a paint app, that allows the drawing of basic shapes and text as well as freehand. Drawings can be saved.

\section{Problem solutions}

\subsection{Show/hide HTML element}
Watch the solution video at \url{http://youtu.be/Pkl4Oxw2q_8}.

\noindent\url{\ftjs show_hide_element.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/show_hide_element.html}}

\subsection{Color preview}
Watch the solution video at \url{https://www.youtube.com/watch?v=qK9jOS2FBpg}.

\noindent\url{\ftjs color_preview.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/color_preview.html}}

\section{Tests}
\subsection{Currency Converter}
\noindent\includegraphics{CurrencyConverter1} 

Create the currency converter shown at \url{http://youtu.be/2QLprjh_f08}.

The user can choose EUR, USD, GBP, JPY or CHF. Get the current exchange rates from the Internet. Currency names and values are stored in arrays.

\subsubsection{Solution}
\noindent\url{\ftjs Tests/CurrencyConverter/Solution/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/CurrencyConverter/Solution/index.html}}

\subsubsection{Pure JS solution}
Here is a solution that illustrates how we can create the whole calculator in JS:
 
\noindent\url{\ftjs Tests/CurrencyConverter/Solution/indexjs.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/CurrencyConverter/Solution/indexjs.html}}

\subsection{Space Ship}
\noindent\includegraphics[width=\linewidth]{SpaceShip1}

Create the page shown at \url{http://youtu.be/lCOYnvVK6vY}  taking the following into account:
\begin{enumerate}
\item Use the skeleton at \url{\ftjs Tests/SpaceShip/index.html}.
\item Create an array with 50 random integers from [1, 200]. If a calculated integer is divisible by 5, it will be doubled. For example, if the random integer is 15, 30 will be the value stored in the array.
\item All array elements are inserted into the drop down list. \textbf{For this step you may not use more than 30 instructions.}
\item The integer selected in the drop down list determines the step size the space ship moves when one of the 4 arrows is clicked.
\item Obviously the space ship may not cross the boundaries of the universe. If it were to based on the step size, it will be placed at the corresponding border.
\end{enumerate}

\subsubsection{Solution}
\noindent\url{\ftjs Tests/SpaceShip/Solution/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/SpaceShip/Solution/index.html}}

\subsection{Space Circuit}
\noindent\includegraphics[width=\linewidth]{SpaceCircuit1}

Create the page shown at \url{http://youtu.be/axrTXBHDbXQ}  taking the following into account:
\begin{enumerate}
\item Use the skeleton at \url{\ftjs Tests/SpaceCircuit/index.html}.
\item Create an empty array \verb|pointXArray| as well as an array \verb|pointYArray|. The latter gets filled with the values at the end of the skeleton.
\item Create function \verb|fillXArray|, which does the following:
\begin{enumerate}
\item Define a variable \verb|xOffset| with a random integer from [1, 400].\item \verb|pointXArray| is filled with values as follows:
\begin{enumerate}
\item Positions 0 to 9 get the value \verb|xOffset + pos * 40|, with \verb|pos| representing the position in the array.
\item Positions 10 to 19 get the value \verb|xOffset + 400 - (pos -10) * 40|.
\end{enumerate}
\end{enumerate}
\item Clicking the button changes its text to "Stop" und calls \verb|fillXArray|. The selected car will then run through the X- and Y-positions stored in the arrays, with a time interval of 100 ms. WHen the end of the array is reached, positions start again at the beginning.
\item Clicking the button again changes the text back to "Loop" and the car animation stops.
\item Clicking the button again ...
\end{enumerate}

\subsubsection{Solution}
\noindent\url{\ftjs Tests/SpaceCircuit/Solution/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/SpaceCircuit/Solution/index.html}}

\subsection{Targeting Practice}
\noindent\includegraphics[width=\linewidth]{TargetingPractice1}

\subsubsection{Solution}
\noindent\url{\ftjs Tests/TargetingPractice/Solution/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/TargetingPractice/Solution/index.html}}

\subsection{Hockenheim Ring}
\noindent\includegraphics[width=\linewidth]{HockenheimRing1}

\subsubsection{Solution}
\noindent\url{\ftjs Tests/HockenheimRing/Solution/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/HockenheimRing/Solution/index.html}}

\subsection{Football Magic}
\noindent\includegraphics[width=\linewidth]{FootballMagic1}

Create a page (\url{http://youtu.be/v5zB0ecaCok}) with a button and a football (\url{https://foxi.ltam.lu/PROF/evegi144/T2IF2_WSERS/WAD/JS/Tests/FootballMagic/football352x352.png}). The CSS for the body background is \verb|background: linear-gradient(darkgreen, lightgreen) fixed;|.

After the document has loaded, an array with 10 randomly generated football positions (x from [0, 600[ and y from [0, 300[) is created.

When the button is clicked, it changes its text from 'Start' to 'Stop' and the ball jumps to the first position in the array, then after 20 ms to the second, after another 20 ms to the third etc. When the ball has reached the last array position, it moves to the first, then the second and so on.

When the button is clicked again, the animation stops and the button text changes back to 'Start'. Clicking it again resumes the animation from the position where it was stopped and changes the text to 'Stop'.

\subsubsection{Solution}
\noindent\url{\ftjs Tests/FootballMagic/Solution/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/FootballMagic/Solution/index.html}}

\subsection{Football Magic v2}
\noindent\includegraphics[width=\linewidth]{FootballMagicv21}

Create the web page shown at \url{http://youtu.be/mRUPjjmpehM} taking the following into account:
\begin{enumerate}
\item The football field has a green background, starts 50 pixels below the upper border and always uses the full window width as well as the remaining window height (i.e. height - 50). To achieve this you need to style the top, right, bottom and left distances of the football field. You can use the \verb|offsetWidth| and \verb|offsetHeight| attributes of the football field.
\item The header includes a \verb|label|, an \verb|input| as well as two \verb|button| elements, only one of which is visible at any point in time.
\item After the start button has been clicked, the ball moves every 20 ms a certain amount of pixels both horizontally and vertically. The pixel number is calculated as a random number between 1 and the value the user has specified in the \verb|input|. If the ball were to move beyond any of the borders, it will be placed at this border and the corresponding direction (vertical or horizontal) changed.
\item After the page has loaded, the user is asked for the password \verb|CLISS1| using the text "Please enter the magic word.". The password will be asked repeatedly until the user enters the correct one. Only thereafter can the animation be started.
\item Your page must pass the HTML5-validator without errors.
\end{enumerate}

\subsubsection{Solution}
\noindent\url{\ftjs Tests/FootballMagicV2/Solution/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/FootballMagicV2/Solution/index.html}}

\subsection{Calculator}
\noindent\includegraphics[width=\linewidth]{Calculator1}

Create the web page shown at \url{http://youtu.be/Fw7PvkvrYss} taking the following into account:
\begin{enumerate}
\item Use the skeleton at \url{\ftjs Tests/Calculator/index.html}.
\item \verb|MC| stands for memory clear, \verb|MR| for memory read and \verb|MS| for memory store. The calculator has two independent memories with initial value 0.  
\item The binary operators \verb|+|, \verb|-|, \verb|*| and \verb|%| work with the two upper inputs fields and write the result into the lower text field. The unary operators uses the upper input field and writes the result there too.
\item The factorial function checks whether the value of the input value is larger than 1000. If so, nothing happens.
\item After the page has loaded, the user is asked for the password \verb|CLISS1| using the text "Please enter the magic word.". The password will be asked up to three times. If after three attempts the user still has not entered the correct password, all document elements will be deleted using \verb|document.body.removeChild(document.querySelector('main'));|.
\end{enumerate}

\subsubsection{Solution}
\noindent\url{\ftjs Tests/Calculator/Solution/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/Calculator/Solution/index.html}}

\subsection{Space Clock}
\noindent\includegraphics[width=\linewidth]{SpaceClock1}

Create the web page shown at \url{http://youtu.be/iNUDJ6zVhYs} taking the following into account:
\begin{enumerate}
\item Part 1
\begin{enumerate}
\item Use the skeleton at \url{\ftjs Tests/SpaceClock/index.html}.
\item Define a two-dimensional array \verb|pixelColorArray|.
\item Write function \verb|fillColorArray|, which fills the array with the RGB value (\verb|"rgb(red part, green part, blue part)"|) for each pixel of a 100 x 100 pixel square. The value for each pixel is calculated like this: red and blue part: \verb|i + j|, green part: \verb|255 - (i + j)|, with \verb|i| and \verb|j| representing the horizontal and vertical pixel position.
\item Write function \verb|drawColorArray|, which draws every pixel with the saved color. Use function \verb|draw|, which is already in the code.
\item Execute the two functions and make sure the result corresponds to what you see in the video.
\end{enumerate}
\item Part 2

Create a copy of \verb|findFirstPos| under the name \verb|fastFindFirstPos| and optimize it in terms of number of variables, instructions and iterations used. To verify your success, some sample instructions have already been created that you can use and extend.
\item Part 3

Below commentary \verb|K3 Debugging| you find 7 lines of buggy JavaScript. Copy and correct them so that the clock is displayed correctly, as shown in the video, without error messages in the console. All variables need to be declared locally.
\end{enumerate}

\subsubsection{Solution}
\noindent\url{\ftjs Tests/SpaceClock/Solution/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/SpaceClock/Solution/index.html}}

%\subsection{Space clock v2}
%\noindent\includegraphics[width=\linewidth]{SpaceClockV21}
%
%Create the web page shown at \url{http://youtu.be/iNUDJ6zVhYs} taking the following into account:
%\begin{enumerate}
%\item Part 1

\subsection{Dog Race}
\noindent\includegraphics{DogRace1}

Create the web page shown at \url{http://youtu.be/_WrlTFUyMhA} taking the following into account:
\begin{enumerate}
\item Use the skeleton at \url{https://foxi.ltam.lu/PROF/evegi144/T2IF2_WSERS/WAD/JS/Tests/DogRace/index.html}.
\item Clicking the button changes its label to "Stop!" and starts the dog race. Clicking the button again changes its label back to "Go!" and halts the race. Clicking it again changes the label and resumes the race etc.
\item Every 20 ms each dog is moved a random number of pixels from [0, 5]. The dog that completely disappears from the screen first wins. If the two dogs disappear at the same time, the message "Draw!" is displayed.
\item You can use the attribute \verb|offsetWidth| to determine the width of the element that contains the two dogs.
\end{enumerate}

\subsubsection{Solution}
\noindent\url{\ftjs Tests/DogRace/Solution/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/DogRace/Solution/index.html}}

\subsection{Crazy Button}
\noindent\includegraphics{CrazyButton1}

Create the web page shown at \url{http://youtu.be/z2tDCjzZH3Y} taking the following into account:
\begin{enumerate}
\item The button initially is labeled "Click me!".
\item Create an array containing 10 random numbers from [0, 1000].
\item With each click on the button, its label changes to the next random number from the array. When the end of the array has been reached, the labeling restarts with the first array element.
\item The button can be moved in steps of 10 pixels using the cursor keys.
\end{enumerate}

\subsubsection{Solution}
\noindent\url{\ftjs Tests/CrazyButton/Solution/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/CrazyButton/Solution/index.html}}

\subsection{MicroJSON}
\noindent\includegraphics{microJSON}

Write a \emph{validated single file} app that does the following (\url{http://youtu.be/1nFOE5cTZrU}) \emph{without any page reload}:
\begin{enumerate}
\item The user can enter a first name and last name. This data is sent to the server using JSON.
\item The server adds a random number to the data received from the client and sends the whole data set (i.e. first name, last name and random number) to the client using JSON.
\item The client displays the three data items.
\end{enumerate}

\subsubsection{Solution}
\noindent\url{\ftjs Tests/MicroJSON/index.php}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html+php}{JS/Tests/MicroJSON/index.php}}

Or using jQuery:

\noindent\url{\ftjs Tests/MicroJSON/index_jquery.php}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html+php}{JS/Tests/MicroJSON/index_jquery.php}}

\subsection{Dice}
\noindent\includegraphics[width=\linewidth]{Dice}

Create a dice simulator with 5 dice (cf. \url{http://youtu.be/oH6I0o3gFxk}).

Upon entering the simulator, the user sees 5 randomly thrown dice as well as a table displaying how often each one of the values 1 to 6 has been thrown so far.

Below the table is a button, which allows to throw the dice again and automatically update the statistics.

When a value appears more than once, all instances are highlighted via CSS.

For the pros: simulate some of the Yahtzee rules (\url{https://en.wikipedia.org/wiki/Yahtzee}).

\subsubsection{Solution}
\noindent\url{\ftjs Tests/Dice/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/Dice/index.html}}

\subsection{Test Stats}
Create a web app that displays basic test statistics (cf. \url{http://youtu.be/_IXETf2fYts}).

The input fields are configured so that they display values outside of [1, 60] as invalid.

Your JavaScript may not produce an error irrespective of the user input.
\subsubsection{Solution}
\noindent\url{\ftjs Tests/TestStats/index.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/TestStats/index.html}}

\subsection{Picture Viewer}
Create the picture viewer shown at \url{http://youtu.be/eZrlapASlIU}.

All HTML elements inside the body as well as all CSS styling must be created in JavaScript.

The picture filenames are stored in an array, so that the application can handle any number of images.
The pictures can be downloaded from \noindent\url{\ftjs Tests/PicViewer}.
The background is a linear gradient to the bottom right from gold to black.

\subsubsection{Solution}
\noindent\url{\ftjs Tests/PicViewer/picviewer.html}
{\scriptsize\inputminted[tabsize=2, linenos=true]{html}{JS/Tests/PicViewer/picviewer.html}}