JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON....

91
JavaScript Jef De Smedt Beta VZW

Transcript of JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON....

Page 1: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

JavaScriptJef De Smedt

Beta VZW

Page 2: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Getting to know…

• Beta VZW: • Association founded in 1993

• Computer courses for the unemployed and for employees

• www.betavzw.org(dutch)

• Cevora VZW/Cefora ASBL

• 09:00u-12:30u

• 13:00u-16:30u

Page 3: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Getting to know… you

• Name

• Role/Function in your organisation

• Experience with• HTML/CSS

• Programming languages

• JavaScript

• Expectations

Page 4: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Overview

• Introduction

• Basic elements of JavaScript

• Arrays

• Window object

• Document Object Model

• Forms

• Events

• Objects

• Introduction to TypeScript

Page 5: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Introduction: what is JavaScript

• Scripting language, 1995, Brendan Eich (Netscape Communications Corporation)

• Ease integration between Java applets and HTML page

<html>

</html>

Java appletJava applet:• Java program in browser• Richer user interface• Compare with Flash, Silverlight• Can only be used when Java is

installed locally

Page 6: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Introduction: what is JavaScript?

• Scripting language, 1995, Brendan Eich (Netscape Communications Corporation)

• Ease integration between Java applets and HTML page

• Dynamic HMTL pages

Page 7: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Introduction: what is JavaScript?

• Scripting language, 1995, Brendan Eich (Netscape Communications Corporation)

• Ease integration between Java applets and HTML page

• Dynamic HMTL pages

• AJAX (Asynchronous JavaScript and XML)

ServerWeb page

XML/JSON

Page 8: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Introduction: history

• Same year(1995): Microsoft, own version (Jscript)

• Compatibility problems

• 1997: standard, European Computer Manufacturers Association

• EcmaScript = “JavaScript language without browser support”

• Implementations of EcmaScript: JavaScript, JScript, ActionScript, …

• Most browsers implement the most important features of EcmaScript6

Page 9: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Introduction: JavaScript = bad programming?

• Not a “real” programming language

• Incompatibilities between different browsers

• Gained popularity because of new libraries and frameworks (JQuery, Modernizr, AngularJS, React, Backbone, …)

• Also more popular on the server side: node.js

Page 10: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

JavaScript vs Java

JavaScript Java

Case sensitive Case sensitive

{…} => blocks {…} => blocks

End statement with semicolon; End statement with semicolon;

Declaration of variables:var i = 42;var name = “John”;var isValid = true;

Declaration of variables:int i = 42;String name = “John”;boolean isValid= true;

Dynamically typedvar i = 42;i = “John”;

Statically typedint i = 42;i = “John”;

The difference between “Java” and “JavaScript” is as big as the difference between “ham” and “hamster”

Page 11: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Write JavaScript code (in a browser)

<!DOCTYPE html>

<html>

<head>

<title>JavaScript</title>

<script>

console.log(“Hi world”);

</script>

</head>

<body>

</body>

</html>

JavaScript code between <script> tags

Attribute type=“text/JavaScript” is notnecessary anymore (default in HTML5)

Page 12: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Write JavaScript code (in a browser)

<!DOCTYPE html>

<html>

<head>

<title>JavaScript</title>

<script src=“index.js”></script>

</head>

<body>

</body>

</html>

Index.html

console.log(“hi world”);

Index.js

Closing script tag is mandatory in HTML5

Page 13: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Write JavaScript code (in a browser)

• Press F12 (developer tools)• Choose Console tab => output of console.log.

Page 14: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Noscript element

• The contents of the <noscript>-element is shown when the browser does not support JavaScript

• <script> and <noscript> are mutually exclusive

<html>

<head>…</head>

<body>

<noscript>Use a browser that supports JavaScript</noscript>

</body>

</html>

Page 15: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Noscript element

• <noscript> can be used in <head> and <body>

• When used in <head> it should only contain <link>, <meta> and<style>elements

• <noscript> can be used in “graceful degradation” => when takingaway JavaScript possibilities the page should still function(more or less)

• Nowadays: “progressive enhancement” => start with a page thatworks without JavaScript and add functionality that makes the page work better.

Page 16: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

JavaScript types

• var i = 42; // number (integer, floating point)

• var name = “John”; //string

• var isValid = true; // boolean

• var value; //undefined

• var empty = null; //null

• var list = [“John”, “Paul”, “Ringo”, “George”]; //object (array)

• var person = {name:”John”, address:”9 Newcastle road”}; //object

• (EcmaScript 6) var s = new Symbol(“key”); //symbol

Page 17: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Working with types

• JavaScript uses dynamic typing:• var i = 7;

i = “John”;

• JavaScript uses type coercion• var number = 4 + “2”;

console.log(number); //42

• See the result of coercion:• Number(“4”); //4• Boolean(1); //true• Boolean(null); // false• String(4); // “4”

The number 4 is coerced intoa string: “4” + “2”. The plus-operator for strings means: concatenate

Page 18: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Prompting and alerting

<!DOCTYPE html>

<html>

<head>

<title>Prompting and alerting</title>

<script>

var number1 = prompt("Give first number");

var number2 = prompt("Give second number");

var sum = number1 + number2;

alert(sum);

</script>

</head>

<body>

</body>

</html>

Prompt-functionreturns a string

Page 19: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Converting to integer

<!DOCTYPE html>

<html>

<head>

<title>Prompting and alerting (int)</title>

<script>

var number1 = prompt("Give first number");

number1 = parseInt(number1);

var number2 = prompt("Give second number");

number2 = parseInt(number2);

var sum = number1 + number2;

alert(sum);

</script>

</head>

<body>

</body>

</html>

parseInt converts a string into a number. (fasterthan Number() in IE and Firefox. See https://jsperf.com/number-vs-parseint-vs-plus)

The fastest way to convert a Stringinto a number in Chrome:number1 = +number1;

Page 20: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Document.write

<!DOCTYPE html>

<html>

<head>

<title>Prompting and alerting (document.write)</title>

<script>

var number1 = prompt("Give first number");

number1 = parseInt(number1);

var number2 = prompt("Give second number");

number2 = parseInt(number2);

var sum = number1 + number2;

document.write(number1 + “ + “ + number2 + “ = “ +sum);

</script>

</head>

<body>

</body>

</html>

document.write writes the argument in de body of the HTML document

Page 21: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

JavaScript arithmetic/string operators

Operator Description Example

+ Adds two numbers var n = 6 + 5; //11

+ Concatenates two strings var n = “6” + “5”; //”65”

- Subtracts two numbers var n = 6 – 5; // 1

* Multiplies two numbers var n = 6 * 5; // 30

/ Divides two numbers var n = 6 / 5; // 1.2

% Takes the modulo(remainder of division)

var n = 6 % 5; // 1

++ Increment operator var n = 6;++n; //7

-- Decrement operator var n = 6;n--;// 5

Page 22: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

JavaScript assignment operators

Operator Description Example

= Assigns a value to another value var a=6, b=8; // a is equal to 6, b is equal to 8

+= Adds a value to a variable var a=6;var a += 3;//9 (a=a+3)

-= Subtracts a value from a variable var a=6;var a -= 3; //4 (a=a-3)

*= Multiply a value and a variable var a=6;var a*= 3; //18 (a=a*3)

/= Divides a variable by a value var a=6;var a/=3; // 2 (a=a/3)

Page 23: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Greetings

Page 24: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Age

Page 25: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

People

Page 26: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

If statement

if (test_that_evaluates_to_true_or_false) {code_that_will_be_executed_when_test_is_true

}

if (test_that_evaluates_to_true_or_false) {code_that_will_be_executed_when_test_is_true

} else {

code_that_will_be_executed_when_test_is_false

}

Page 27: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

If statement example

var now= new Date();

var hour = now.getHours();

if (hour < 12){

alert(“Good morning");

}else{

alert(“Good afternoon");

}

Page 28: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

If statement example

var now = new Date();

var hour = now.getHours();

if (hour == 9){

document.write(“Around nine: coffee time");

}else if (hour==12) {

document.write(“Between twelve and one: everyone is gone");

}else if (hour == 17){

document.write(“Seventeen?: bring in the caffeine");

}else{

document.write(“Time to work");

}

Page 29: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

JavaScript equality operators

Operator Description Example

== Compares two values for equality var a=7, b=“7”;var test = a == b; //true

=== Compares two values and theirtypes for equality

var a=7, b=“7”;var test = a === b;//false

!= Compares two values for inequality var a=7, b=“7”;var test = a != b; //false

!== Compares two values and theirtypes for inequality

var a=7, b=“7”;var test = a!== b; //true

Page 30: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

JavaScript comparison operators

Operator Description Example

< Less than var a=7, b=8;var test = a < b; //true

> Greater than var a=7, b=6;var test = a > b;//true

<= Less than or equal var a=7, b=7;var test = a <= b; //true

>= Greater than or equal var a=7, b=7;var test = a>= b; //true

Instanceof Is Object of certain type var d = new Date();var test = d instanceof Date; // true

Page 31: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

JavaScript logical operators

Operator Description Example

&& And (both must be true in order forthe result to be true)

var a=true, b=false;var test = a && b; //false

|| Or (At least one must be true in order for the result to be true)

var a=true, b=false;var test = a || b;//true

! Not (true becomes false and falsebecomes true)

var a=true;var test = !a; //false

Page 32: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Profit/loss

What do you do whenincome equals expenses?

Page 33: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

What is your name?

An empty string in JavaScript: “” or ‘’ (two single quotes)

Page 34: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Old enough to visit website(at least 18)

Can you write it in such a way that it will still work correctly next year (i.e. not only in 2017?)

Page 35: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Switch statement

switch(value) {

case n: code_to_execute_when_value_equals_n

break;

case m: code_to_execute_when_value_equals_m

break;

default: code_to_execute_in_all_other_cases

}

Page 36: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Switch statement example

var now = new Date();

var hour = now.getHours();

switch(hour){

case 9:

document.write(“Around nine: coffee time");

break;

case 12:

document.write(“Between twelve and one: everyone is gone");

break;

case 18:

document.write(“Seventeen?: bring in the caffeine");

break;

default:

document.write(“Time to work");

}

Just an extra question: does a switchuse == or === for equality? Try it out.

Page 37: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Calculator

This should also work for operators: -, / and *. When the user chooses a non existing operatorthe program should show:

Page 38: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

While statement

while(test_that_evaluates_to_true_or_false) {

code_to_execute_as_long_as_test_is true

//do not forget to change the outcome of the test

}

Page 39: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

While statement example

var sum = 0;

var n = parseInt(prompt(“Give number (<0 to stop“);

while (n >= 0)

{

sum = sum + n;

n = parseInt(prompt(“Give number (<0 to stop");

}

document.write(“The sum equals " + sum);

Page 40: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Name is required

Page 41: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

For statement

for(initial;test;change) {

code_to_execute

}

Is the same as

Initial

while(test) {

code_to_execute

change

}

Page 42: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

For statement example

• The following while:

var i = 0;

while (i < 3){

console.log(i);

i++;

}

• Is the same as this for

for(var i=0;i<3;i++) {

console.log(i);

}

Page 43: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Arrays

• Arrays are lists of itemsvar list = [“John”, “Paul”, “George”, “Ringo”];• An item in an array can be accessed by using the index (zero-based):var item = list[0];//”John”• Number of elements: lengthvar n = list.length;//4• Using a for-loop:for (var i=0; i<list.length;i++){

console.log(list[i]);}

Page 44: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Simple Array functionsFunction Description Example

indexOf(element) Returns the position of the first occurence of an element in an Array (not found: -1)

var l = [“John”,”Paul”,”Ringo”,”George”];var n = l.indexOf(“John”);//0

join(separator) Joins the elements into a string. Default separator is comma

var l = [“John”,”Paul”];var n=l.join();//”John,Paul”

lastIndexOf(element) Returns the position of the last occurence of an element in an Array (not found: -1)

var l = [“John”,”Paul”,”Ringo”,”George”];var n = l.lastIndexOf(“John”);//0

pop() Removes the last element of thearray and returns it

var l = [“John”,”Paul”];var n=l.pop();//n=“Paul”, l=[“John”];

push(element) Adds an element to the end of anarray and returns the length

var l=[“John”];var n=l.push(“Paul”);//n=2, l=[“John”,”Paul”]

reverse() Reverse the order of the elements var l=[“John”,”Paul”];l.reverse(); //[“Paul”,”John”]

sort() Sorts the element of an array var l=[“Paul”,”John”];l.sort();//[“John”,”Paul”]

Page 45: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Example of for and array function

<!DOCTYPE html>

<html>

<head>

<title>for+array example</title>

<script>

var list = [];

for (var i=0;i<3;i++) {

var name = prompt("Give name " + (i+1));

list.push(name);

}

document.write(list.join(", "));

</script>

</head>

<body>

</body>

</html>

Page 46: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Create an ordered(ol) list

Page 47: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Licence plates

What to do when the licenceplate was not found?

Page 48: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Working with strings

• Let us start with an example

var text = prompt("Give some text");

var counter = 0;

for (var i=0;i<text.length;i++){

if (text.charAt(i) == 'i') counter ++;

}

document.write(“The text contains the character

\"i\" " + counter + " times");

Page 49: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

String functions

Function Description Example

length Returns the number of characters(length is not a function)

var text=“John”;var n = text.length; //4

charAt(position) Returns the character at the specifiedposition(zero based)

var text=“John”;var c = text.charAt(1): // ‘o’

includes(text) Returns true when text is part of the string var text=“John;var t = text.includes(“oh”);//true

indexOf(text) Returns the first position of text. (or -1 iftext is not found)

var text=“Joohn”;var i = text.indexOf(“o”);//1

lastIndexOf(text) Returns the last position of text. (or -1 if textis not found)

var text=“Joohn”;var i = text.lastIndexOf(“o”);//2

slice(start, end) Returns the part of the string that starts at start and ends at end (not included)

var text=“John”;var n = text.slice(1, 2);//”o”

split(separator) Splits the string on the separator andreturns an array with the substrings

var text=“John,Paul”;var l = text.split(“,”);//[“John”,”Paul”]

Page 50: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Draw square (sort of)

Page 51: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Functions

• Blocks of JavaScript code that can be used (“called”) in a script

• There are existing functions (e.g. document.write(), prompt()) but we can also declare them ourselves

• function name_of_the_function(arguments_of_the_function) {code_for_the_function

}

• Example

function sum(number1, number2) {return number1 + number2;

}

Page 52: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Calling functions

• To use a function, we have to “call” it:alert(“Hi all”);

• To use our sum-function:var result = sum(1,2);

function sum(number1, number2) {

return number1 + number2;

} 1 2

3 <=

Page 53: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Example of a function

<script>

var text = prompt("Give e-mail");

if (isValidEmail(text)){

document.write(text + " is a valid e-mail address.");

} else {

document.write(text + " is not a valid e-mail address.");

}

function isValidEmail(mail) {

if (mail.indexOf("@") == -1){

return false;

}

return true;

}

</script>

The function returns a boolean => it canbe used in if(), while(), …

Valid email: contains a ‘@’

Page 54: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Using callback functions

• A function can take simple types as arguments: number, string, boolean, object

• But it can also take another function as argument

• ex.: array function findIndex takes as argument a function

• The function is called for each element of the argument

• When the function returns true, the iteration stops and the index of that element is returned by findIndex

Page 55: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Using callback functions

• E.g. an array var ages = [3, 10, 18, 20];

• A callback function:function checkAdult(age) {

return age >= 18;

}

• ages.findIndex(checkAdult)

will return return 2 (the index of the first element that is greater than or equal to 18)

Page 56: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Using callback functions

• Writingdocument.write(ages.findIndex(checkAdult));

is the same as:for(var i=0;i<ages.length;i++){

if (checkAdult(ages[i])){

document.write(i);

break;

}

}

Page 57: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

More elaborate email test

• Continue with the previous example

• A valid e-mail address should only contain one @• John@[email protected] is not a valid email address

• It must contain text before the ‘@’• @liverpool.ac.uk is not a valid email address

• It should also contain at least one dot (.) after the @• Paul@liverpool is also not a valid email address

• Tip: add the tests one at the time

Page 58: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Is it a palindrome (e.g. level)

<!DOCTYPE html><html>

<head><title>Square</title><script>

var text = prompt("Give text");if (isPalindrome(text)){

document.write(text + " is a palindrome.");} else {

document.write(text + " is not a palindrome.");}

//write the function here</script>

</head><body></body>

</html>

A palindrome is a word that reads the same backward orforward. Add a function to test whether a word is a palindrome.

Page 59: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Is it a valid IBAN number

• There are some calculations involved when we want to check an IBAN number (bank account).

• We just want to check the form BExx-xxxx-xxxx-xxxx• Total length: 19 characters

• Start with “BE”

• 5th, 10th and 15th character must be “-”

• Extra: all x’s should be digits

• Write a function in JavaScript to test the form of an IBAN number anduse that function in an HTML page.

Page 60: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Filter: starting with capital

Create a file exfuncfilter.js so that the HTML page shows a commaseparated list of all names that start with a capital

<!DOCTYPE html>

<html>

<head>

<script>

var list = ["John", "paul", "Ringo", "George"];

</script>

<script src="exfuncfilter.js"></script>

</head>

<body>

</body>

</html>

Page 61: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Variable scope

• A variable that is declared in a function is local

var value = 42;

doSomething();

console.log(value); // value is still 42

function doSomething() {

var value = 2016;

}

Page 62: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Intermezzo: variable “hoisting”

<script>

console.dir(window);

var v2 = v1;

var v1=42;

</script>

<script>

console.dir(window);

var v2 = v1;

//var v1 = 42;

</script>

Is there a difference?

V2 is undefined becausev1 got its value on thenext line.

Error because v1 does not exist

Page 63: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Intermezzo: variable “hoisting”

• Functions will be hoisted before variables

• => when a function and a variable have the same name (don’t ever do this), the function will “win” because it is declared first.

var x;

function x(){

console.log("h");

}

console.log(typeof x); //function

Page 64: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Intermezzo: variable “hoisting”

• However, when we initialize the variable, this initialisation will occurafter the hoisting and it will overwrite the function

var x = 5;

function x(){

console.log("h");

}

console.log(typeof x); //number

Page 65: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Intermezzo: variable “hoisting”

<script>

console.dir(window);

var v2 = v1;

var v1=42;

</script>

The declarationof a variable is “hoisted” to thetop

var v1

Page 66: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Intermezzo: variable “hoisting”

<script>

var v1;

console.dir(window);

var v2 = v1;

v1=42;

</script>

The declarationof a variable is “hoisted” to thetop

On this line v1 is declared but undefined.

Page 67: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Variable scope (EcmaScript 6)

if(true){

let i=7;

}

console.log(i); // undefined

• Starting with EcmaScript 6 we can have variables in block scopeby using “let” instead of “var” for declarations.

Page 68: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

“use strict”

• In the past JavaScript was a “flexibel” (=messy) language

• We can make it behave more strict using “use strict” => puts theengine in strict-mode

• “use strict” uses quotation marks so that older scripts do not see it as an unknown keyword.

• “use strict” works per file or per <script>-element

Page 69: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Some consequences of “use strict”

• Variables must be declared:x = 42; //not allowed

• Deleting a variable is not allowedvar x = 42;delete x; // not allowed

• Duplicate argument names are not allowedfunction DoSomething(arg1, arg1) { // not allowed

• Writing to a read only property is not allowedvar name =“John”;

name[0] = “j”; //not allowed

Page 70: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

The document object

• Access the HTML elements in JavaScript => Document Object Model (DOM)

<html><head></head><body><ol><li>one</li><li>two</li></ol></body></html>

html

head

body

ol

li

li

one

one

Child element

Parent element

Text element

The DOM-tree

Page 71: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

The document object

• Link between DOM-tree (in memory) and JavaScript: the document object

<!DOCTYPE html>

<html>

<head>

<title>The document object</title>

<script>

console.dir(document);

</script>

</head>

<body>

</body>

</html>

Page 72: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Intermezzo: Document Object Model

• Standard not only used for HTML, also for XML (https://www.w3.org/DOM/)

• Not only used in JavaScript, but also in other languages: Java, PHP, C#, …

• Different levels: level-0 (html soup), level-1, level-2, level-3, level-4(work in progress)

• What is the difference between childnodes and children?(both DOM level-1)

Page 73: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

The document object

• In HTML every element can have a unique id.

• JavaScript can get an element based on its id: document.getElementById(“theID”);

• ID’s are unique => only one element will be returned

• BUT the element must be available in the DOM-tree

Page 74: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

The document object

<!DOCTYPE html>

<html>

<head>

<title>The document object</title>

<script>

var elH1 = document.getElementById("heading");

console.dir(elH1);

</script>

</head>

<body>

<h1 id="heading">Title</h1>

</body>

</html>

html

head

script

?

Because the h1-element does not exist yet when the JavaScript code is executed,the result of getElementById is null (empty)

Page 75: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

The document object

<!DOCTYPE html>

<html>

<head>

<title>The document object</title>

</head>

<body>

<h1 id="heading">Title</h1>

<script>

var elH1 = document.getElementById("heading");

console.dir(elH1);

</script>

</body>

</html>

html

head

script

body

h1#heading Title

The h1-element does exist when the JavaScript code is executed,so getElementById returns a result

Page 76: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

The text of an element

• A text is a childnode

• But there are also special attributes with which to get the text:• textContent: not supported in IE8, not CSS aware in Firefox (will show hidden

text)

• innerText: CSS aware in Firefox (will not show hidden tekst)

• innerHTML: all browsers, will include HTML as HTML

• Solution: jQuery text() (cross browser)

Page 77: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

The text of an element

<!DOCTYPE html>

<html>

<head>

<title>Copy values</title>

</head>

<body>

<h1 id="heading">Title</h1>

<div id="body"></div>

<script>

var elH1 = document.getElementById("heading");

var elBody = document.getElementById("body");

elBody.textContent = elH1.textContent;

</script>

</body>

</html>

Page 78: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

The value attribute

• (some) Elements have textnode children

• The text of an <input>-element is not a textnode

• <input type=“text“ id=“name” name=“name” value=“John”/><!DOCTYPE html>

<html>

<head>

<title>Value attribute</title>

</head>

<body>

<h1 id="heading">John</h1>

<input type="text" id="name" name="name" value="nobody"/>

<script>

var elH1 = document.getElementById("heading");

var elName = document.getElementById("name");

elName.value = elH1.textContent;

</script>

</body>

</html>

Quite often attributes can beaccessed as properties

elName.setAttribute("value", elH1.textContent);

A more generic way is using setAttribute andgetAttribute.

Page 79: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Buttons

<!DOCTYPE html>

<html>

<head>

<title>Value attribute</title>

</head>

<body>

<h1 id="heading">John</h1>

<input type="submit" id="btn1" />

<button id="btn2"></button>

</body>

</html>

Give both buttons the text of the H1-element

Page 80: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Clicking on a button

• The onclick attribute of a button => execute “piece of JavaScriptcode”

• To define a “piece of JavaScript code” we use functionsfunction DoSomething(){

alert(“Hi all”);

}

• General form:function name(arguments) {

code}

• To execute a function: DoSomething()

Page 81: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Clicking on a button

<!DOCTYPE html>

<html>

<head>

<title>OnClick attribute</title>

<script>

function SayHi() {

alert("Hi all");

}

</script>

</head>

<body>

<h1 id="heading">John</h1>

<button id="btn2" onclick="SayHi();">Say hi</button>

</body>

</html>

A function is executed when it is called, not when it is read by the browser

JavaScript code to execute the function.

Page 82: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Integrating a form with JavaScript

<!DOCTYPE html>

<html>

<head>

<title>Working with fields</title>

<script>

function SayHi() {

var name = document.getElementById("txtName").value;

var resultField = document.getElementById("result");

resultField.textContent = "Hi " + name;

}

</script>

</head>

<body>

<form>

Name: <input type="text" id="txtName"/>

<input type="button" onclick="SayHi();" value="Say hi"/>

<div id="result"></div>

</form>

</body>

</html>

Page 83: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Onclick property vs Onclick attribute

• Instead of using the HTML onclick attribute we can also use the JavaScript onclickproperty

• (compare to: HTML value attribute and JavaScript value property)<body>

<form>

Name: <input type="text" id="txtName"/>

<input id="btn" type="button" value="Say hi"/>

<div id="result"></div>

<script>

var btn = document.getElementById("btn");

btn.onclick = SayHi;

</script>

</form>

</body>

Page 84: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Onclick property vs Onclick attribute

• Two remarks• We have to put the script near the end of the dom-tree. Otherwise

document.getElementById(“btn”) cannot find the button.

• We do not use the call-operator (two round brackets: SayHi())

• Using the call operator like this:btn.onclick = SayHi();

would call the function and store the result in btn.onclick

• We want to assign the function SayHi to the property onclick

Page 85: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Why use btn.onclick instead of < … onclick=…> ?• We want to separate the JavaScript code from the HTML code

• Compare to styles: in most cases you should not use the styleattribute in HTML

• Clear separation between HTML and JavaScript is one of theprinciples of unobtrusive JavaScript: the site should still work without JavaScript

• Let us look at an example

Page 86: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

The obtrusive way

• This will not work if JavaScript is disabled and there is no way to make it work:

<a

href="javascript:window.open('http://www.w3.org/wiki/The

_principles_of_unobtrusive_JavaScript')">W3C Article</a>

• The following will work if JavaScript is disabled but it is a maintenance nightmare

<a

href="http://www.w3.org/wiki/The_principles_of_unobtrusi

ve_JavaScript"

onclick="window.open('http://www.w3.org/wiki/The_princip

les_of_unobtrusive_JavaScript');return false;">W3C

Article</a>

Page 87: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

The unobtrusive way

<a class="newwindow" href="http://www.w3.org/wiki/The_principles_of_unobtrusive_JavaScript">W3C Article</a>

<script>

var anchors = document.getElementsByClassName("newwindow");

for (var i=0; i<anchors.length;i++) {

anchors[i].onclick = OpenWindow;

}

function OpenWindow(){

window.open(this.href);

return false;

}

</script>

return false: Do not execute thedefault behavior (=follow link)

The keyword this refersto the <a>-element

Page 88: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Calculation with select

Create a form with two input fields, a drop down (select)field, a button and a span-element. The drop downshould contain “+”, “-”, “*” and “/”

When the user fills in two numbers, chooses an operatorand clicks the button…

… the result must be shown in the span element

Page 89: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Window object

• In a browser, the window object is the top-level item

• Everything we declare is stored in this object

<!DOCTYPE html>

<html>

<head>

<title>The window object</title>

<script>

console.dir(window);

</script>

</head>

<body>

</body>

</html>

Console.dir shows thestructure of an object.

Page 90: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Window object(chrome)

Page 91: JavaScript - Beta VZW · •AJAX (Asynchronous JavaScript and XML) Web page Server XML/JSON. Introduction: history •Same year(1995): Microsoft, own version (Jscript) •Compatibility

Window object<script>

var value=42;console.dir(window);

</script> Every variable we declarebecomes an item in thewindow object.

We declare a variabele here