Javascript DOM Javascript main properties n n n

  • Slides: 41
Download presentation
Javascript & DOM

Javascript & DOM

Javascript – main properties n n n n is a lightweight scripting language (language

Javascript – main properties n n n n is a lightweight scripting language (language used to control the browser) that is run on the client-side (browser) developed by Netscape and Sun Microsystems and introduced first in the Netscape Navigator 2. 0 is intended to add interactivity and dynamic functionality to HTML pages is interpreted, not compiled, inserted directly in HTML pages is an object-oriented language that inherits many features from Java, but it is not Java is understood by most browsers is an event-based language, weakly typed current standard version is ECMAScript 2018 (ES 9), but browser conformance is ECMAScript 2015 (ES 6) -2016 (ES 7)

What can Javascript do ? n n n it can detect the type of

What can Javascript do ? n n n it can detect the type of browser it can react to various events of the browser it can alter the structure of the html document (modify, delete, add tags on the run-time) it can validate data before being sent to the server it can not modify local (client) files

Base elements of Javascript n n Js inherits from Java simple data types, operators,

Base elements of Javascript n n Js inherits from Java simple data types, operators, instruction syntax Js has predefined objects: DOM-related and general objects: Array, Boolean, Date, Error, Eval. Error, Function, Math, Number, Object, Range Error, Reference. Error, Reg. Exp, String, Syntax. Error, Type. Error, URIError n n n Js has some global functions (not related to objects): decode. URI, decode. URIComponent, encode. URIComponent, eval, is. Finite, is. Na. N, parse. Float, parse. Int comments: // or /*…*/ Js is weakly-typed: a variable can be bound to a specific type, then to a different type, during the course of a program execution

Types and literals (constant values) n n n n numbers: integer (in base 2,

Types and literals (constant values) n n n n numbers: integer (in base 2, 8, 10, 16) and real boolean: true and false null undefined: a variable that does not have an assigned value; Na. N: not a number String: ‘text’, “something”, `text 1` etc. ; methods of the string class can be applied on any string literal (e. g. “sir”. length); `` can span over multiple lines vectors: [‘a’, , , ‘bbb’, ‘ccc’] will have 5 elements objects: lists of zero or more pairs “property : value” ex. : dog = {name: dog, type: animal, characteristics: get. Props(“dog”), age: 4}

Variables n loosly-typed language: n n a variable can be bound to different types

Variables n loosly-typed language: n n a variable can be bound to different types during its lifetime; the value of a variable is automatically converted to other types when necessary the type of a variable needs not be declared a variable is declared with “var” or just by assigning a value to it: var name; root=“some text”; i = root+1; // i=“some text 1”

Variables (cont. ) n n n a variable without a value assigned to it

Variables (cont. ) n n n a variable without a value assigned to it will be evaluated to “undefined” or Na. N (depending on the context) if it was declared with “var” or will give a run -time error if it was not declared with “var” a variable is global (decl. outside any function) or local to a function or has block scope (if declared with let ) function variables: var f = function(a, b) { return a+b; } f(2, 3) ; // calling the function

Operators n n n n 3 types of expressions in Js: arithmetic (eval. to

Operators n n n n 3 types of expressions in Js: arithmetic (eval. to a number), string and boolean (eval. to true or false) assign operators: =, +=, -=, *=, /=, %=, <<=, >>>=, &=, ^=, |= comparison operators: ==, !=, >, >=, <, <= arithmetic operators: %, /, ++, --, +, bitwise operators: &, |, ^, ~, >>, <<, >>> logic operators: &&, ||, ! string operator: + (concatenation) special operators

Special operators n n n n n identity operators: === (eguality and of the

Special operators n n n n n identity operators: === (eguality and of the same type), !== (not equal and/or of different types) ternary operator: condition ? true-expr : false-expr comma: expr 1, expr 2, …, expr. N new: creates a new object this: refers to the calling object in a method typeof: typeof(“test”) => string delete: deletes an object or a property from an object or an element from a vector in: prop. Nameor. Number in object. Name instanceof: object. Name instanceof object. Type void: evaluates an expression without returning a value

Instructions (borrowed from Java) n n n conditional: if, switch “falsy values”: false, undefined,

Instructions (borrowed from Java) n n n conditional: if, switch “falsy values”: false, undefined, null, 0, Na. N, “” loop: for, do while, label, break [label], continue [label] for (variable in object) { … statements …} : cycles through the properties of an object for (variable of object) { … statements …} : “for. . . in” cycles over property names, “for. . . of” iterates over property values: with (object) { … statements … } : sets the default object for a set of statements exception handling instructions: try { … statements … } catch (exception) { … } throw expression;

For cycles. . var a = [ 'x', 'y', 23 ]; a. Test =

For cycles. . var a = [ 'x', 'y', 23 ]; a. Test = “foo”; for (i=0; i<a. length; i++) { console. log(a[i]); } // will print: x, y, 23 for (var i in a) { console. log(i); } // will print: 0, 1, 2, test for (var i of a) { console. log(i); } // will print: x, y, 23

Functions n n usually they are declared in the <head> tag and called all

Functions n n usually they are declared in the <head> tag and called all over the html file the syntax of declaring a function is: function name_fct(parameters, arguments) { … statements … } where parameters represent specific parameters sent to the function, arguments contain a variable number of arguments; the variable arguments can be accessed inside the function through arguments[i], where i goes from 0 to arguments. length n all primitive parameters are passed to the function by value; only object properties changes are visible outside the function (if param is an object)

Function expressions n Function names can be used as arguments for other functions or

Function expressions n Function names can be used as arguments for other functions or values for variables function cubic(x) { return x*x*x; } var square. Func. Var = function square (x) { return x*x; } function map(f, a) { for(i=0; i<a. length; i++) { console. log(f(a[i])); } } var v = [ 1, 2, 3 ]; map(cubic, v); // will print 1, 8, 27 map(square. Func. Var, v); // will print 1, 4, 9

Creating functions using the Function constructor var sum = new Function(‘x’, ‘y’, ‘return x+y’);

Creating functions using the Function constructor var sum = new Function(‘x’, ‘y’, ‘return x+y’); sum(2, 3); § § § functions created with the Function() constructor do not create closures to their creation context, they are created in the global context they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called all functions are actually objects (of the prototype Function)

Anonymous functions Ex. 1: var square = function(a) { return a*a; } square(2); //

Anonymous functions Ex. 1: var square = function(a) { return a*a; } square(2); // calling the function Ex. 2: (function(a) { return a*a; }) (3); // this function is auto-called after the declaration; returns 9

Function scope n n variables defined inside a function can not be accessed outside

Function scope n n variables defined inside a function can not be accessed outside the function but a function can access all variables from the scope in which it is defined: n n n if the function is defined in global scope, it can access all variables defined in the global scope if the function is defined inside another function, it can access all variables (and parameters) defined by its parent function and all variables to which the parent function has access functions are hoisted (i. e. in the same file, they can be called before the line in which they are defined)

Inner functions and closures n n n a nested (inner) function can only be

Inner functions and closures n n n a nested (inner) function can only be accessed from statements in the outer function the inner function forms a closure: the inner function can use the parameters and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function a closure provides a form of encapsulation for the variables of the inner function

Closure example function outer(a, b) { var c = 3; function inner (x, y)

Closure example function outer(a, b) { var c = 3; function inner (x, y) { // a, b, and c are all accessible here x = x+y+c*(a+b); return x; } inner(a, b); }

Default parameters function sum(a, b = 0) { return a+b; } sum(2); // returns

Default parameters function sum(a, b = 0) { return a+b; } sum(2); // returns 2

Arrow function expressions (have shorter syntax) n n (param 1, param 2, …, param.

Arrow function expressions (have shorter syntax) n n (param 1, param 2, …, param. N) => { statements } (param 1, param 2, …, param. N) => expression equivalent to: => { return expression; } n n n parentheses are optional when there's only one parameter name: (single. Param) => { statements } single. Param => { statements } the parameter list for a function with no parameters should be written with a pair of parentheses: () => { statements }

Arrow function expressions (cont. ) var materials = [ 'Hydrogen', 'Helium', 'Lithium', 'Beryllium']; console.

Arrow function expressions (cont. ) var materials = [ 'Hydrogen', 'Helium', 'Lithium', 'Beryllium']; console. log(materials. map( m => m. length)); // will output: Array [8, 6, 7, 9]

Collections (creation and iteration) n Creating arrays var array 1 = new Array(2, 3,

Collections (creation and iteration) n Creating arrays var array 1 = new Array(2, 3, 5); var array 2 = Array(“abc”, “de”, “fghij”); var array 3 = [0, “abc”, 2]; var array 4 = new Array(array. Length); var array 5 = Array(array. Length); n Iterating over arrays for (var i = 0; i <array 3. length; i++) { console. log(array 3[i]); } array 3. for. Each(function(elem) { console. log(elem); }); array 3. for. Each(elem => console. log(elem));

Collections (Array methods) n n n concat() joins two arrays and returns a new

Collections (Array methods) n n n concat() joins two arrays and returns a new array join(delimiter = ', ') joins all elements of an array into a string push() adds one or more elements to the end of an array and returns the resulting length of the array. pop() removes the last element from an array and returns that element shift() removes the first element from an array and returns that element slice(start. Index, upto. Index) extracts a section of an array and returns a new array.

Collections (Array methods; cont. ) n n n splice(index, count. To. Remove, add. Element

Collections (Array methods; cont. ) n n n splice(index, count. To. Remove, add. Element 1, add. Element 2, . . . ) removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array reverse() transposes the elements of an array, in place: the first array element becomes the last and the last becomes the first. It returns a reference to the array sort() sorts the elements of an array in place, and returns a reference to the array index. Of(search. Element[, from. Index]) searches the array for search. Element and returns the index of the first match for. Each(callback[, this. Object]) executes callback on every array item and returns undefined. map(callback[, this. Object]) returns a new array of the return value from executing callback on every array item

Classes and objects n n n Js is a prototype-based language, it does not

Classes and objects n n n Js is a prototype-based language, it does not distinct between a class and a class instance (object); it only has objects; current object referred with “this” An object is an associative array augmented with a prototype creating objects can be done in 3 ways: n using an object initializer: object. Name = {property 1: value 1, property 2: value 2, . . . , property. N: value. N} n using a constructor function: function print() {…} function Thing(x, y, z) { this. prop 1=x; this. prop 2=y; this. prop 3=z; this. method 1=print; } ob = new Thing(a, b, c); § creating an empty object first and then adding properties to it: var person = new Object(); person. name=“Forest”; person. age=25; n n n objects are deleted using “delete object. Name” properties are accessible by obj. property or obj[index_property] or obj[“property”] new properties can be added to object on run-time: obj. new. Prop=val

Predefined objects n n n n Array – working with arrays (sort, push etc.

Predefined objects n n n n Array – working with arrays (sort, push etc. ) Boolean – true or false Function – specifies a string of code to be precompiled as a function Date – date functions Math – math functions Number – numerical constants and representations Reg. Exp – regular expressions String – string operations

Events n n Javascript is an event-based language Event: mouse click, key pressed, element

Events n n Javascript is an event-based language Event: mouse click, key pressed, element loosing focus etc. when an event is triggered by the browser a predefined or user-defined (in Javascript) event handler takes control event handlers are associated to a tag: 1) <TAG event. Handler=“Javascript code”> 2) <script type=“text/javascript”> function ev. Handle(x) { … } </script> <TAG event. Handler=“ev. Handle(this)”> 3) <script type="text/javascript"> obj. event. Handler=“Javascript code”; </script>

Events (2)

Events (2)

Javascript and HTML Js scripts can be used in HTML documents in 4 ways:

Javascript and HTML Js scripts can be used in HTML documents in 4 ways: 1) as instructions or functions written inside a <SCRIPT> tag: n <script type=”text/javascript”> … Java. Script statements. . . </script> 2) Js code written in a separate javascript file: <script src="common. js"></script> 3) using a Js expression as the value of an html attribute: <hr width="&{bar. Width}; %" align=“left"> <h 4>&{my. Title}; </h 4> Java. Script entities start with “&” and end with “; ” and are enclosed in “{}” 4) as an event handler: <input type="button" value="Press Me" on. Click="func()">

Pop-up boxes n n n alert(“…text…”) : displays text and the Ok button confirm(“…

Pop-up boxes n n n alert(“…text…”) : displays text and the Ok button confirm(“… text…”) : displays text and returns true if the Ok button is clicked and false if the Cancel button is clicked prompt(“text”, “default value”): the user can enter an input value and then click Ok (return the value) or Cancel (return null)

DOM (Document Object Model) n n n is a standardized (by W 3 C)

DOM (Document Object Model) n n n is a standardized (by W 3 C) hierarchical model of an HTML or XML document DOM can be used for navigating in the document structure, modify the document structure (add, delete, modify child elements etc. ) and also modifying attributes of an element each tag is a DOM object it has an API which can be used in Javascript + DOM is sometimes called DHTML (Dynamic HTML)

DOM Browser Objects n n n Window object Navigator object Screen object History object

DOM Browser Objects n n n Window object Navigator object Screen object History object Location object

DOM document objects n n n n Document object Anchor object Area object Base

DOM document objects n n n n Document object Anchor object Area object Base object Body object Button object Event object Form object Frameset object IFrame object Image object Input Button object Input Checkbox object Input File object n. Input Hidden object n. Input Password object n. Input Radio object n. Input Reset object n. Input Submit object n. Input Text object n. Link object n. Meta object n. Object object n. Option object n. Select object n. Style object n. Table. Cell object n. Table. Row object n. Textarea object

Document object collections Collection Description forms[] Returns a reference to all Form objects in

Document object collections Collection Description forms[] Returns a reference to all Form objects in the document images[] Returns a reference to all Image objects in the document links[] Returns a reference to all Area and Link objects in the document anchors[] Returns a reference to all Anchor objects in the document

Document object properties Property Description body Gives direct access to the <body> element cookie

Document object properties Property Description body Gives direct access to the <body> element cookie Sets or returns all cookies associated with the current document domain Returns the domain name for the current document last. Modified Returns the date and time a document was last modified referrer Returns the URL of the document that loaded the current document title Returns the title of the current document URL Returns the URL of the current document

Document object methods Method Description close() Closes an output stream opened with the document.

Document object methods Method Description close() Closes an output stream opened with the document. open() method, and displays the collected data get. Element. By. Id() Returns a reference to the first object with the specified id get. Elements. By. Name() Returns a collection of objects with the specified name get. Elements. By. Tag. Name() Returns a collection of objects with the specified tagname open() Opens a stream to collect the output from any document. write() or document. writeln() methods write() Writes HTML expressions or Java. Script code to a document writeln() Identical to the write() method, with the addition of writing a new line character after each expression

Asynchronous programming var timeout. ID = window. set. Timeout(func, delay, [param 1, param 2,

Asynchronous programming var timeout. ID = window. set. Timeout(func, delay, [param 1, param 2, . . . ]) Calls function “funct” with the specified parameters after “delay” miliseconds have passed. n window. clear. Timeout(timeout. ID); Clears the timeout (async function is no longer called). n

Asynchronous programming (promises) const my. First. Promise = new Promise(function (resolve, reject) { //

Asynchronous programming (promises) const my. First. Promise = new Promise(function (resolve, reject) { // do something asynch which eventually calls either: // resolve(some. Value); // fulfilled // or // reject("failure reason"); // rejected }); The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions, when called, resolve or reject the promise, respectively. The executor normally initiates some asynchronous work, and then, once that completes, either calls the resolve function to resolve the promise or else rejects it if an error occurred. If an error is thrown in the executor function, the promise is rejected. The return value of the executor is ignored.

Browser API, Web API, Js libraries, Js frameworks n n Browser API – a

Browser API, Web API, Js libraries, Js frameworks n n Browser API – a set of javascript functions, objects & properties exposed by the browser; e. g. DOM; a list of browser APIs developed by w 3 c. org is here: https: //www. w 3. org/standards/techs/js#w 3 c_all Web API – a server-side API usually exposed through HTTP requestresponse; the response is usually a JSON expression Js library – one or more js files providing custom functions & objects that enhance the functionality of the javascript language; e. g. j. Query Js framework – a js library plus html & css code used to write an entire web application from scratch; inversion of control – key difference between libraries and frameworks: when calling a method from a library, the developer is in control; with frameworks control is inverted – the framework calls developer’s code; e. g. angular js

Js debugging tools n n n Firefox’s Web Console and Chrome’s Inspector Js. Fiddle

Js debugging tools n n n Firefox’s Web Console and Chrome’s Inspector Js. Fiddle (https: //jsfiddle. net/) Code. Pen (https: //codepen. io)

Additional Documentation n n http: //www. cs. ubbcluj. ro/~forest/wp http: //www. w 3 schools.

Additional Documentation n n http: //www. cs. ubbcluj. ro/~forest/wp http: //www. w 3 schools. com/js/default. asp http: //www. w 3 schools. com/jsref/dom_obj_document. asp https: //developer. mozilla. org/en/Java. Script