Pro Yearly is on sale from $80 to $50! »

JavaScript and jQuery - Lecture 6 - Web Technologies (1019888BNR)

1135dc242dcff3b90ae46fc586ff4da8?s=47 Beat Signer
October 30, 2020

JavaScript and jQuery - Lecture 6 - Web Technologies (1019888BNR)

This lecture forms part of the course Web Technologies given at the Vrije Universiteit Brussel.

1135dc242dcff3b90ae46fc586ff4da8?s=128

Beat Signer

October 30, 2020
Tweet

Transcript

  1. 2 December 2005 Web Technologies JavaScript and jQuery Prof. Beat

    Signer Department of Computer Science Vrije Universiteit Brussel beatsigner.com
  2. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 2

    October 30, 2020 JavaScript ▪ High-level loosely typed dynamic language ▪ Introduced by Netscape in 1995 ▪ lightweight interpreted client-side programming ▪ Supports imperative, object-oriented and functional programming styles ▪ Nowadays also used in non-web-based environments ▪ PDF, Microsoft Office, … ▪ JavaScript implements the ECMAScript specification ▪ latest version is ECMAScript 2019 [https://insights.stackoverflow.com/survey/2020] Most Popular Programming, Scripting, and Markup Languages
  3. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 3

    October 30, 2020 Adding JavaScript to a Webpage ▪ JavaScript code can be placed in the <head>, in the <body> or in external files <!DOCTYPE html> <html> <head> <tile>JavaScript Example</tile> ... <script> alert("Message in the header"); </script> <script src="example.js"></script> </head> <body> <h1>A First Example</h1> <script> document.write("<p>Text added by JavaScript</p>"); </script> <p id="p2">A second paragraph.</p> </body> </html>
  4. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 4

    October 30, 2020 Adding JavaScript to a Webpage … ▪ Advantages of external JavaScript files ▪ separation of HTML and code ▪ faster page load if JavaScript file is cached ▪ JavaScript code placed just before the </body> tag (end of the page) might improve page load ▪ display of HTML is not blocked by script loading ▪ alternative: attribute defer="true" in the <script> tag ▪ JavaScript errors silently ignored by most browsers ▪ activate browser console for debugging (e.g. F12) ▪ Use the latest version of the language by adding "use strict"; to the top of a script
  5. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 5

    October 30, 2020 Browser Console ▪ Error 'aalert' shows up in the console
  6. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 6

    October 30, 2020 Output ▪ There are different possibilities for JavaScript output ▪ document.write() ▪ adds content to the page while loading ▪ deletes (overwrites) page if used after page has been loaded ▪ should only be used for testing (slow) ▪ console.log() ▪ outputs content to the browser console ▪ window.alert() or alert() ▪ outputs data in an alert message box ▪ innerHTML property ▪ adds content to an HTML element (via DOM tree) document.getElementById("p2").innerHTML = "A new second paragraph.";
  7. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 7

    October 30, 2020 Variables and Data Types ▪ Variables have dynamic types ▪ Primitive data types ▪ string, number and boolean ▪ null and undefined ▪ Objects let x; // x has been declared but the value is 'undefined' x = "Albert Einstein"; // now x is a string x = 3.1415; // now x is a number typeof x; // number x = false; // now x is a boolean
  8. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 8

    October 30, 2020 Strings ▪ Any text between single (') or double quotes (") ▪ Strings are immutable ▪ Special characters (e.g. '\', '\t' or '\n') have to be escaped with a backslash (\) let hello = "Hello World"; let correct = "This is \"correct\""; // escaped double quotes let tmp = hello.length; // 11 tmp = hello + ". " + correct; // Hello World. This is "correct" tmp = hello.charAt(1); // e tmp = hello.toUpperCase(); // HELLO WORLD tmp = hello.replace("World", "VUB"); // replace first occurence of 'World' with 'VUB'
  9. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 9

    October 30, 2020 Numbers ▪ Only one type of numbers (64-bit floating point) ▪ mantissa (52 bits), exponent (11 bits) and sign (1 bit) ▪ NaN indicates that a value is not a number ▪ Infinity for values that are too large to be represented let x = 42.00; let y = 42; let z = 42e3; // 42000 let x = 42 / "foo"; // but what about 'x = 42 + "foo"? isNaN(x); // returns true // what is the difference between '10 + 10 + "foo"' and '"foo" + 10 + 10'? let x = 42 / 0; // x becomes Infinity
  10. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 10

    October 30, 2020 Numbers … ▪ Rounding errors ▪ due to rounding errors we might not always get the expected result let x = 0.3 + 0.6; // 0.8999999999999999 let x = (0.3 * 10 + 0.6 * 10) / 10; // possible solution (resulting in 0.9)
  11. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 11

    October 30, 2020 Boolean ▪ Booleans can have the values true or false let x = true; let y = false; let z = 5 > 3; // true
  12. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 12

    October 30, 2020 Date and Math Objects ▪ Date object can be used to work with dates ▪ Math object can be used for various mathematical operations and offers some constans (e.g. PI and E) let now = new Date(); let nextWeek = new Date("2017-11-10T14:00:00"); // ISO 8610 syntax let milis = now.getTime(); // time in milliseconds since January 1, 1970 let test = nextWeek.getTime() > now; // true Math.random(); // random number between 0 (inclusive) and 1 (exclusive) Math.round(3.6); // 4 (rounded to the nearest integer) Math.max(4,10,3); // 10 (number with the highest value)
  13. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 13

    October 30, 2020 Objects ▪ Container of properties (name/value) where a value can be any JavaScript value (including other objects) ▪ Two possibilities to retrieve object values ▪ second option only works for legal JavaScript names and non-reserved words let student = { firstName: "John", lastName: "Harper", height: 182 }; student["firstName"]; student.lastName;
  14. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 14

    October 30, 2020 Objects ... ▪ Existing values can be updated, new properties can be added and existing properties can be deleted ▪ Objects are passed by reference and not by value ▪ Cloning of objects (deep copy) is not trivial in JavaScript ▪ e.g. jQuery offers a clone() method student.lastName = "Wayne"; student.address = { street: "Pleinlaan", number: 2 }; delete student.lastName; let x = student; // student object created before x.firstName = "Peter"; let name = student.firstName; // name is "Peter" since x and student are references // to the same object
  15. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 15

    October 30, 2020 Arrays ▪ An array is a variable that can hold multiple values which can be accessed via an integer offset ▪ values of different types might be mixed ▪ Other methods to sort arrays, combine arrays etc. let points = [10, 5, 17, 42]; points.length; // number of elements (4) points[1]; // accesses the element with the given offset (5) points[points.length] = 13; // adds 13 to the end of the array [10, 5, 17, 42, 13] let last = points.pop(); // removes the last element [10, 5 , 17 , 42] let l = points.push(2); // adds 2 at the end and returns the length (5) let first = points.shift(); // removes the first element [5, 17, 42, 2] l = points.unshift(7); // adds 7 to the beginning and returns the length (5) delete points[2]; // the third element will be undefined let matrix = [[3, 1, 2], [9, 6, 4], [5, 7, 8]]; // array of arrays ("2D" array) matrix [1][2]; // 4
  16. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 16

    October 30, 2020 Functions ▪ A function is a block of code to perform a particular task ▪ enables the reuse of code ▪ functions are objects and can be used like any other value - can be stored in variables, objects and arrays - can be passed as argument to functions or returned from functions ▪ access to a function without the () operator returns the definition of a function function multiply(p1, p2) { return p1 * p2; } let r = multiply(3, 4); // 12
  17. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 17

    October 30, 2020 Scope ▪ Local variables declared within a function have block-level scoping ▪ A variable declared outside of a function has global scope ▪ Local variables deleted when the block is completed ▪ Function arguments (parameters) work as local variables within functions ▪ Warning ▪ old var syntax does not offer block-level scoping but rather provides function scoping
  18. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 18

    October 30, 2020 Objects Revisited ▪ Functions can be added to objects (methods) Multiple objects can be created via an object constructor function (prototype) // Let us assume that we have the student object that was created earlier student.fullName = function() { return this.firstName + " " + this.lastName; } function student(firstName, lastName, height) = { this.firstName = firstName; this.lastName = lastName; this.height = height; this.fullName = function() {return this.firstName + " " + this.lastName;} }; let student1 = new student("Audrey", "Sanctorum", 174); let student2 = new student("Maxim", "Van de Wynckel", 177);
  19. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 19

    October 30, 2020 Classes ▪ Classes have been introduced in ECMAScript 2015 ▪ simplifies inheritance etc. class Person { constructor(firstName, lastName, height) { this.firstName = firstName; this.lastName = lastName; this.height = height; } fullName() { return this.firstName + " " + this.lastName; } } class Student extends Person { constructor(firstName, lastName, height, studentID) { super(firstName, lastName, height); this.studentID = studentID; } }
  20. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 20

    October 30, 2020 Classes … let student = new Student("Audrey", "Sanctorum", 174, 93283982); console.log(student.fullname()); // Audrey Sanctorum console.log(student instanceof Person); // true console.log(student instanceof Student); // true
  21. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 21

    October 30, 2020 Modules ▪ Modules can be used to control the scoping instead of using a shared-everything approach ▪ export keyword to expose code to other modules ▪ exported functionality can be accessed from another module via the import keyword export let counter = 0; export function multiply(p1, p2) { return p1 * p2; } ... import multiply from "./example.js"; ...
  22. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 22

    October 30, 2020 Conditional Statement ▪ Used to perform different actions based on different conditions let mention = ""; if (grade < 10) { mention = "Fail"; } else if (grade < 13.6) { mention = "Pass"; } else if (grade < 15.4) { mention = "Distinction"; } else if (grade < 17) { mention = "Great Distinction"; } else { mention = "Greatest Distinction"; }
  23. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 23

    October 30, 2020 Loops ▪ For Loop ▪ For/In Loop ▪ iterate over object properties ▪ While Loop for (let i = 0; i < 10; i++) { text += "Number: " + i + "<br />"; } for (x in student) { text += " " + student[x]; // Add all properties of 'student' to text string } while (i < 10) { text += "Number: " + i + "<br />"; i++; }
  24. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 24

    October 30, 2020 Events ▪ Various events can be triggered when accessing an HTML document ▪ document has finished loading ▪ form field has been changed ▪ button has been clicked ▪ mouse is moved over an image ▪ ... ▪ JavaScript can be used to trigger some actions when events are detected <button onclick="startSlideshow()">Start</button>
  25. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 25

    October 30, 2020 JavaScript Best Practices ▪ Avoid (minimise) global variables ▪ global variables can lead to name collisions for sub-programs but modules can be used to fix the problem ▪ Always initialise variables when they are declared ▪ avoids undefined values ▪ Always use the === and !== equality operators ▪ == and != do some automatic type coercion (with complicated rules) if the types are not equal
  26. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 26

    October 30, 2020 JavaScript Best Practices ... ▪ Avoid block-less if, while, do or for statements ▪ Avoid the use of eval() ▪ runs text as code and leads to performance and security issues if (x > 10) { t = true; }
  27. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 27

    October 30, 2020 jQuery ▪ JavaScript library that simplifies the use of JavaScript on websites ▪ HTML/DOM traversal and manipulation ▪ event handling ▪ effects and animation ▪ AJAX ▪ Most popular and extendable JavaScript framework ▪ large developer community ▪ Two ways to add jQuery to a website ▪ download jQuery library (JavaScript file) from jquery.com ▪ link to jQuery library on content delivery network (CDN) server - Microsoft, Google, …
  28. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 28

    October 30, 2020 jQuery ... ▪ jQuery code executed when document loaded (ready) <!DOCTYPE html> <html> <head> <tile>jQuery Example</tile> ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $(document).ready(function(){ // jQuery code }); </script> </head> <body> ... </body> </html>
  29. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 29

    October 30, 2020 DOM Revisited ▪ cross-browser issues when accessing DOM via JavaScript News html head body document title Vrije Univer ... h1 p p … … a Internation ... Vrije Uni ... href http:// ... root node document.getElementsByTagName("h1"); document.getElementById("main"); JavaScript
  30. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 30

    October 30, 2020 jQuery Syntax ▪ jQuery syntax makes it easy to select HTML elements (based on CSS-style selectors) and perform some actions on these elements ▪ $ sign to access jQuery followed by a selector and the action to be performed on the selected elements ▪ Examples $(selector).action(); $("h1").hide(); // hide all h1 elements (implicit iteration) $("h1").hide().delay(500).fadeIn(1500); // multiple methods can be chained $("h1:first").hide(); // hides the first h1 element $("#main").hide(); // hides the element with id=main $(".note").toggle(); // toggles all elements of class note $("p:even").toggle(); // toggles all even paragraph elements $("h1").html(); // get content from first h1 element $("h1").each(function() {...}); // loop over each h1 element $("p").html("New"); // updates the content of all p elements to "New"
  31. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 31

    October 30, 2020 Caching jQuery Selections ▪ A jQuery object (result of a selection) has references to the elements in the DOM tree ▪ if the same selection is used multiple times, the jQuery object can be reused (cached) by storing it in a variable let $paragraphs = $("p"); // often prefix $ used for variables with a jQuery object
  32. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 32

    October 30, 2020 Attributes ▪ Attributes can be accessed and updated ▪ Similar functionality exists for classes $("a:first").attr("href"); // get the href attribute of the first anchor tag $("a:first").attr("href", "http://wise.vub.ac.be"); // update attribute $("a:first").removeAttr("href"); // remove href attribute of the first anchor tag $("p").addClass("main"); // adds an additional class $("p").removeClass("main"); // removes the class main
  33. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 33

    October 30, 2020 Event Handling ▪ Deals with cross-browser issues behind the scenes ▪ There are various jQuery events from different sources ▪ keyboard - input, keydown, keyup, keypress ▪ mouse - click, dblclick, mouseup, mousedown, mouseover, mousemove, mouseout, hover ▪ UI - focus, blur, change ▪ form - submit, select, change ▪ document - ready, load, unload
  34. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 34

    October 30, 2020 Event Handling ... ▪ We can handle events via the on() method ▪ the first parameter is the event to respond to and the second parameter is a named or anonymous function $("#start").on("click", startSlideshow();); // calls a named function $("p").on("mouseover", function(e) { // anonymous function $(this).hide(); });
  35. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 35

    October 30, 2020 DOM Navigation ▪ Various methods can be used to start navigating the DOM tree from a given selection ▪ parent() - direct parent of current selection ▪ parents() - all parents of current selection ▪ children() - all children of current selection ▪ next () - next sibling of current selection ▪ siblings() - all siblings of current selection ▪ ...
  36. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 36

    October 30, 2020 Other JavaScript Libraries ▪ jQuery UI ▪ various widgets and effects ▪ jQuery Mobile ▪ touch optimised interaction for mobile devices ▪ Modernizr.js ▪ check availability of certain features in a browser ▪ D3.js ▪ interactive data visualisations
  37. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 37

    October 30, 2020 JavaScript Object Notation (JSON) ▪ Developed as an XML alternative to represent JavaScript objects as strings (language independent) ▪ Easy to produce and faster to parse than XML ▪ supports different data types ▪ JSON is based on a subset of JavaScript ▪ JSON document can be read via the JavaScript eval() function - security issues: note that this approach can be dangerous if the source is not trusted since any JavaScript code might be executed ▪ most recent browsers offer a JSON parser - recognises only JSON data types and rejects any scripts ▪ Many Web 2.0 Applications offer a JSON interface ▪ Flickr, YouTube, Delicious, ...
  38. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 38

    October 30, 2020 JSON Data Types ▪ The values themselves can be simple values (number, boolean or string), arrays or objects ▪ nesting is supported Type Description Number integer, real or float Boolean true or false String double-quoted Unicode (use backslash for escaping) Array comma-separated ordered sequence of values enclosed in square brackets Object comma-separated collection of key:value pairs enclosed in curly brackets null null value
  39. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 39

    October 30, 2020 JSON Syntax Diagrams http://www.json.org
  40. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 40

    October 30, 2020 JSON Example { "surname": "Signer", "forename": "Beat", "address": { "street": "Pleinlaan 2", "city": "Brussels", "postalCode": 1050, "country": "Belgium" }, "phoneNumbers": [ { "type": "office", "number": "123 456 789" }, { "type": "fax", "number": "987 654 321" } ] }
  41. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 41

    October 30, 2020 Exercise 6 ▪ JavaScript and HTML5 APIs
  42. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 42

    October 30, 2020 References ▪ JavaScript: The Definitive Guide: Master the World's Most-used Programming Language, David Flanagan, O'Reilly (7th edition), May 2020, ISBN-13: 978-1491952023 ▪ JavaScript: The Good Parts, Douglas Crockford, O'Reilly Media (1st edition), May 2008, ISBN-13: 978-0596517748 Understanding ECMAScript 6: The Definitive Guide for JavaScript Developers, Nicholas C. Zakas, No Starch Press (1st edition), October 2016 ISBN-13: 978-1593277574
  43. Beat Signer - Department of Computer Science - bsigner@vub.ac.be 43

    October 30, 2020 References ... ▪ JavaScript Tutorial ▪ https://javascript.info/ ▪ jQuery Tutorial ▪ http://www.w3schools.com/jquery/ ▪ JSLint: The JavaScript Code Quality Tool ▪ https://www.jslint.com
  44. 2 December 2005 Next Lecture XML and Related Technologies