Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript...

36
Javascript and the DOM Introduzione alla programmazione web – Marco Ronchetti 2020 – Università di Trento 1

Transcript of Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript...

Page 1: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Javascript and the DOM

Introduzione alla programmazione web – Marco Ronchetti 2020 – Università di Trento1

Page 2: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

http

d

The web architecture with smart browser

Inter

net

Cgi-binQuery SQL

proc

ess

DB

DataClient

Server

File SystemSmartbrowser

HTTP Get + params

Evolution 3: execute code also on client! (How ?)

The web programmer also writesPrograms which run on the browser.Which language? Javascript!

Page 3: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Javascript and the DOM1- Adding dynamic behaviour to HTML

Introduzione alla programmazione web – Marco Ronchetti 2020 – Università di Trento3

Page 4: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Example 1: onmouseover, onmouseout<!DOCTYPE html><html>

<head><title>Dynamic behaviour</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width,

initial-scale=1.0"></head><body>

<div onmouseover="this.style.color = 'red'"onmouseout="this.style.color = 'green'">I can change my colour!</div></body>

</html> JAVASCRIPTThe dynamic behaviour is on the client side!(The file can be loaded locally)

Page 5: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Example 2: onmouseover, onmouseout<body><div onmouseover="this.style.background='orange';this.style.color = 'blue';"

onmouseout="this.innerText='and my text and position too!';this.style.position='absolute'; this.style.left='100px’;this.style.top='150px';this.style.borderStyle='ridge';this.style.borderColor='blue';this.style.fontSize='24pt';">

I can change my colour...</div>

</body >

Page 6: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

JavaScript is event-based

UiEvents:These event objects iherits the properties of the UiEvent:• The FocusEvent• The InputEvent• The KeyboardEvent• The MouseEvent• The TouchEvent• The WheelEvent

See https://www.w3schools.com/jsref/obj_uievent.asp

Page 7: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Test and Gym

HTML HEAD

HTML BODY

JAVASCRIPT

CSS

https://www.jdoodle.com/html-css-javascript-online-editor/

Page 8: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Javascript and the DOM2- Introduction to the language

Introduzione alla programmazione web – Marco Ronchetti 2020 – Università di Trento8

Page 9: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

JavaScript History• JavaScript was born as Mocha, then “LiveScript” at the

beginning of the 94’s.• Name changed into JavaScript (name owned by Netscape)• Microsoft responds with Vbscript• Microsoft introduces JScript (dialect of Javascript)• A standard is defined: ECMAScript (ECMA-262, ISO-

16262)• Jscript survives (as ECMAScript incarnation till 2009,

then as Chakra till 2015)• Another incarnation of ECMAScript is ActionScript

(Adobe, for Flash)

Page 10: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

JavaScript: History

Introduzione alla programmazione web – Marco Ronchetti 2020 – Università di Trento10

Name Edition Date publishedMocha May-95LiveScript Sep-95JavaScript Dec-95

Jscript Aug-96 MicrosoftECMAScript 1 Jun-97ECMAScript 2 Jun-98 ActionScript 1998 Macromedia/AdobeECMAScript 3 Dec-99ECMAScript 4 AbandonedECMAScript 5 Dec-09ECMAScript 5,1 Jun-11ECMAScript 2015 (ES2015) 6 Jun-15ECMAScript 2016 (ES2016) 7 Jun-16ECMAScript 2017 (ES2017) 8 Jun-17ECMAScript 2018 (ES2018) 9 Jun-18ECMAScript 2019 (ES2019) 10 Jun-19

Page 11: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

ECMAScript EngineAn ECMAScript engine is a program that executes source code written in a version of the ECMAScript language standard

See https://en.wikipedia.org/wiki/List_of_ECMAScript_engines

Examples:

•V8 (Chrome, NodeJS, Opera)•SpiderMonkey (Mozilla)•Chakra (Microsoft)•JavaScriptCore(Apple)•Nashorn (Oracle – JDK)

Page 12: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

JavaScript Myths

§JavaScript is NOT simple§Simple tasks are indeed simple

§JavaScript is NOT Java

Java JavaScript

Browser Control NO YESNetworking YES Partial

Graphics YES Partial

Page 13: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

JavaScript is…

§ Scripted (not compiled)§ Powerful§ Cross-Platform

§ Client and Server

§ Object-based(and partially oriented)

§ Event-driven

JavaScript allows…

§ Dynamic Web Sites § Dynamic HTML (DHTML) § Interactive Pages/Forms § Server-Side Functionality § Application Development

Page 14: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

JavaScript and HTML

• Between <script> and </script> tags• In a <script src="url"></script> tag• Between <server> and </server> tags• In an event handler:<input type="button" value="Click me"

onClick="js code"><div onmouseover="this.style.color = 'red'" onmouseout="this.style.color = 'green’”>

Page 15: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Base• Syntax is C-like (C++-like, Java-like)

case-sensitive,statements end with (optional) semicolon ;//comment /*comment*/operators (=,*,+,++,+=,!=,==,&&,…)

Page 16: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Statements

• if (expression) {statements} else{statements}

• switch (expression) {case value: statements; break;…

default: statements; break;}

• while (expression) {statements} • do (expression) while {statements}• for (initialize ; test ; increment)

{statements}

for (a in s) {statements}

Page 17: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Data types• Primitive data types

number, string, boolean, undefined

• Complex data typesobject, function (more later!)

• Loosely, dynamic typed variables (Basic-like) t0==typeof(x);var x=3;var t1=typeof(x);x="pippo";var t2=typeof(x);

t0: undefined

t1: number

t2: string

Page 18: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Data types: Objects and DOMJavascript also has Objects, somehow similar to Java Objects (even though their implementation is quite different, and their definition not as clean and straightforward as in Java).

Objects have variables and methods.

Similarly to Java Objects, they can be printed: in such case they use their customized toString() method, or give a generic indication such as [object HTMLDivElement]

Some Javascript Objects represent fragments of an HTML document. The collection of these Objects represent the whole page. Such representation is called Document Object Model.

Page 19: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Operators• Mathematical operators: standard, plus ** for exponentiation

(ES6)• Assignment operators: standard, plus **= for exponentiation

(ES6)• String operators: + (concatenation), see later• Comparison operators: standard, plus type and value

• Logical and bitwise operators: standard• Type operators

=== equal value and equal type

!== not equal value or not equal type

typeof Returns the type of a variable

instanceof Returns true if an object is an instance of an object type

see https://www.w3schools.com/js/js_operators.asp

Page 20: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

More here:

https://www.w3schools.com/js/default.asp

it is suggested to quicklygo through these items!

Page 21: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Javascript and the DOM3- user input and output

Introduzione alla programmazione web – Marco Ronchetti 2020 – Università di Trento21

Page 22: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

User I/OCore

<BODY><H2>Table of Numbers </H2><SCRIPT>

n=window.prompt("Give me the value of n",3);for (i=1; i<n; i++) {

document.write(i);document.write("<BR>");

}</SCRIPT></BODY></HTML>

Using document.write() after an HTML document isloaded, will delete allexisting HTML:The dynamic behaviour is

on the client side!(The file can be loaded locally)

Page 23: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

JS output

Writing into the HTML output using document.write().Writing into an alert box, using window.alert().Writing into the browser console, using console.log().

Page 24: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

JS outputWriting into an HTML element, using:• innerHTML<div onmouseover="this.innerHTML='How are you?';">

Hello</div>

• innerText<div onmouseover="this.innerText='How are you?';">

Hello</div>

• textContent<div onmouseover="this.textContent='How are you?';">

Hello</div>

Page 25: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

JS output

<div onmouseover="window.alert(this.property)";>This element contains <code>code</code>, <span

style="visibility:hidden">hidden information, </span>and <strong>strong language</strong>.</div>

• innerHTML

• innerText

• textContentText only,

CSS unaware

Text only,CSS aware

Full HTML content

property

Page 26: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

What is "this"?

<div onmouseover="window.alert(this)";"> Hello</div>

[object HTMLDivElement]

li -> [object HTMLLiElement]

<a onmouseover="window.alert(this)";" href="http://localhost"> a link</a>

a -> http://localhost

b, i -> [object HTMLElement]

h1,…h5 -> [object HTMLHeadingElement]

<b onmouseover="window.alert(this.nodeName)";"> Hello</b>

b -> ba -> a

Page 27: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Javascript: the language4- Taking a look at strings

Introduzione alla programmazione web – Marco Ronchetti 2020 – Università di Trento27

Page 28: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

StringsJavaScript Strings are a strange, double-headed beast…

They are both a primitive data type andan object

View also:https://www.w3schools.com/js/js_strings.asp

Page 29: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Strings as ObjectsUsually, JavaScript strings are primitive values, created

from literals:

var firstName_primitive = "John";

But strings can also be defined as objects with the keyword new:

var firstName_object = new String("John");

When using === , firstName_primitive and firstName_object are NOT EQUAL, because the === operator expects equality in both type and value. With == they are EQUAL.

Page 30: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

String operators

a+b => football

a<b => true

Page 31: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

String methodsThere are a lot of java-like methods

Some examples:charAt(0)indexOf(substring), lastIndexOf(substring)charCodeAt(n),fromCharCode(value,…)concat(value,…),slice(start,end)toLowerCase(), toUpperCase()replace(regexp,string), search(regexp)

• List: https://www.w3schools.com/jsref/jsref_obj_string.asp(Ignore constructor and prototype for now)

• Detailed examples: https://www.w3schools.com/js/js_string_methods.asp

Page 32: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Javascript: the language5 - getting deeper: plus operator – part 1

Introduzione alla programmazione web – Marco Ronchetti 2020 – Università di Trento32

Page 33: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

+ Operator : rulesoperand1 + operand2 = result

Phase 1: conversion1) Any Object operand is converted to a primitive value

(String, Number, Boolean); 2) If an operand is a String and the other is not, the non-

String operand is converted to String3) Any remaining Boolean operand is converted to Number

(true->1, false->0)4) Any remaining null operand is converted to Number (0)5) Any remaining Undefined is converted to Number (NaN)

Phase 2: execution6) If both operands are String, concatenation is performed.7) If both operands are Number, sum is performed.

Page 34: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

+ Operator : examples without instantiated Objects

x y Is there a String operand? x+y

1 2 NO 3

"1" 2 YES -> Rule 2 12

1 null NO -> Rule 4 1

"1" null YES -> Rule 2 1null

1 undefined NO-> Rule 5 NaN

"1" undefined YES -> Rule 2 1undefined

1 true NO ->Rule 3 2

"1" true YES -> Rule 2 1true

false true NO ->Rule 3 1

true null NO ->Rule 3, 4 1

true undefined NO->Rule 3, 5 NaN

null null NO ->Rule 4 0

null undefined NO->Rule 4, 5 NaN

Page 35: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

Operations with integers <script>var x = "100"; var y = "10";

document.write(x * y);document.write("<br>");document.write(x + y);document.write("<br>");document.write(x * 1 + y);document.write("<br>");document.write(x * 1 + y * 1);document.write("<br>");</script>

OUTPUT:10001001010010110

Page 36: Javascriptand the DOM - UniTrentolatemar.science.unitn.it/segue_userFiles/2021Programma...•Jscript survives (as ECMAScript incarnation till 2009, then as Chakra till 2015) •Another

+ as unary operatorUnary + can be used to convert string to number

var y = "5"; // y is a stringvar x = + y; // x is a number (5)

var y = "Pippo"; // y is a stringvar x = + y; // x is a number (NaN)