1 / 41

Javascript & DOM

Javascript & DOM. Javascript – main properties. 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

jupton
Download Presentation

Javascript & DOM

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Javascript & DOM

  2. Javascript – main properties • 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 (ES9), but browser conformance is ECMAScript 2015 (ES6) -2016 (ES7)

  3. What can Javascript do ? • 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

  4. Base elements of Javascript • Js inherits from Java simple data types, operators, instruction syntax • Js has predefined objects: DOM-related and general objects: Array, Boolean, Date, Error, EvalError, Function, Math, Number, Object, Range Error, ReferenceError, RegExp, String, SyntaxError, TypeError, URIError • Js has some global functions (not related to objects): decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, eval, isFinite, isNaN, parseFloat, parseInt • 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

  5. Types and literals (constant values) • 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; • NaN: not a number • String: ‘text’, “something”, `text1` 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: getProps(“dog”), age: 4}

  6. Variables • loosly-typed language: • 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 text1”

  7. Variables (cont.) • a variable without a value assigned to it will be evaluated to “undefined” or NaN (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

  8. Operators • 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

  9. Special operators • identity operators: === (eguality and of the same type), !== (not equal and/or of different types) • ternary operator: condition ? true-expr : false-expr • comma: expr1, expr2, …, exprN • 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: propNameorNumber in objectName • instanceof: objectName instanceof objectType • void: evaluates an expression without returning a value

  10. Instructions (borrowed from Java) • conditional: if, switch “falsy values”: false, undefined, null, 0, NaN, “” • loop: for, do while, 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;

  11. 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

  12. Functions • 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 • all primitive parameters are passed to the function by value; only object properties changes are visible outside the function (if param is an object)

  13. Function expressions • Function names can be used as arguments for other functions or values for variables function cubic(x) { return x*x*x; } varsquareFuncVar = 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(squareFuncVar, v); // will print 1, 4, 9

  14. 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)

  15. 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

  16. Function scope • 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: • 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)

  17. Inner functions and closures • 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

  18. 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); }

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

  20. Arrow function expressions (have shorter syntax) • (param1, param2, …, paramN) => { statements } • (param1, param2, …, paramN) => expression equivalent to: => { return expression; } • parentheses are optional when there's only one parameter name: (singleParam) => { statements } singleParam => { statements } • the parameter list for a function with no parameters should be written with a pair of parentheses: • () => { statements }

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

  22. Collections (creation and iteration) • Creating arrays var array1 = new Array(2, 3, 5); var array2 = Array(“abc”, “de”, “fghij”); var array3 = [0, “abc”, 2]; var array4 = new Array(arrayLength); var array5 = Array(arrayLength); • Iterating over arrays for (var i = 0; i <array3.length; i++) { console.log(array3[i]); } array3.forEach(function(elem) { console.log(elem); }); array3.forEach(elem => console.log(elem));

  23. Collections (Array methods) • 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(startIndex, uptoIndex) extracts a section of an array and returns a new array.

  24. Collections (Array methods; cont.) • splice(index, countToRemove, addElement1, addElement2, ...) 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 • indexOf(searchElement[, fromIndex]) searches the array for searchElement and returns the index of the first match • forEach(callback[, thisObject]) executes callback on every array item and returns undefined. • map(callback[, thisObject]) returns a new array of the return value from executing callback on every array item

  25. Classes and objects • 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: • using an object initializer: objectName = {property1:value1, property2:value2,..., propertyN:valueN} • using a constructor function: function print() {…} function Thing(x, y, z) { this.prop1=x; this.prop2=y; this.prop3=z; this.method1=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; • objects are deleted using “delete objectName” • properties are accessible by obj.property or obj[index_property] or obj[“property”] • new properties can be added to object on run-time: obj.newProp=val

  26. Predefined objects • 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 • RegExp – regular expressions • String – string operations

  27. Events • 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 eventHandler=“Javascript code”> 2) <script type=“text/javascript”> function evHandle(x) { … } </script> <TAG eventHandler=“evHandle(this)”> 3) <script type="text/javascript"> obj.eventHandler=“Javascript code”; </script>

  28. Events (2)

  29. Javascript and HTML • Js scripts can be used in HTML documents in 4 ways: 1)as instructions or functions written inside a <SCRIPT> tag: <script type=”text/javascript”> … JavaScript 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="&{barWidth};%" align=“left"> <h4>&{myTitle};</h4> JavaScript entities start with “&” and end with “;” and are enclosed in “{}” 4)as an event handler: <input type="button" value="Press Me" onClick="func()">

  30. Pop-up boxes • 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)

  31. DOM (Document Object Model) • is a standardized (by W3C) 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 • Javascript + DOM is sometimes called DHTML (Dynamic HTML)

  32. DOM Browser Objects • Window object • Navigator object • Screen object • History object • Location object

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

  34. Document object collections

  35. Document object properties

  36. Document object methods

  37. Asynchronous programming • vartimeoutID = window.setTimeout(func, delay, [param1, param2, ...]) Calls function “funct” with the specified parameters after “delay” miliseconds have passed. • window.clearTimeout(timeoutID); Clears the timeout (async function is no longer called).

  38. Asynchronous programming (promises) const myFirstPromise = new Promise(function (resolve, reject) { // do something asynch which eventually calls either: // resolve(someValue); // 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.

  39. Browser API, Web API, Js libraries, Js frameworks • Browser API – a set of javascript functions, objects & properties exposed by the browser; e.g. DOM; a list of browser APIs developed by w3c.org is here: https://www.w3.org/standards/techs/js#w3c_all • Web API – a server-side API usually exposed through HTTP request-response; 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. jQuery • 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

  40. Js debugging tools • Firefox’s Web Console and Chrome’s Inspector • JsFiddle (https://jsfiddle.net/) • CodePen (https://codepen.io)

  41. Additional Documentation • http://www.cs.ubbcluj.ro/~forest/wp • http://www.w3schools.com/js/default.asp • http://www.w3schools.com/jsref/dom_obj_document.asp • https://developer.mozilla.org/en/JavaScript

More Related