Unit 2 Class Notes
Unit 2 Class Notes
Feedback/corrections: vibha@pesu.pes.edu
document
html
head body
img h1 p
div script
img h1 p
ID #demo getElementByID('demo')
div script
img h1 p
Parent relationship
body
parentNode parentNode
div script
img h1 p
Sibling relationship
nextSibling
div script
previousSibling
nextSibling nextSibling
img h1 p
previousSibling previousSibling
Code Example
Note: <script> tags in the head of the document: the document isn't yet populated with the
hierarchy of DOM objects yet
Solution 1: add <script> tags after elements - not elegant
Solution 2: add an init() function onload
Must define the init() function in <script>
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>DOM Manipulation</title>
7 <script type="text/javascript" src="1-dom.js">
8
9 </script>
10 </head>
11 <!-- Add onload="init()" for DOM access in script tags
12 Once the page has been loaded, the hierarchy is available
13 (must define function init() in script)
14 -->
15 <body onload="init()">
16 <h1>Games</h1>
17 <ul>
18 <li>Call of Duty</li>
19 <li class="g1">Fortnite</li>
20 <li class="g1">PUBG</li>
21 </ul>
22
23 </body>
24 </html>
1 function init() {
2 h1 = document.querySelector("h1");
3 h1.style.color = "blue";
4
5 list = document.querySelectorAll("li.g1");
6 for (i=0; i<list.length; i++) {
7 /* Convert to uppercase */
8 list[i].innerText = list[i].innerText.toUpperCase();
9 }
10
11 /* Add new element to DOM */
12 new_li = document.createElement('li');
13 new_li.innerText = "Assassin's Creed";
14
15 /* Select the ul element */
16 ul1 = document.querySelector('ul');
17
18 /* Add element to end (appendChild) - uncomment this */
19 // ul1.appendChild(new_li);
20
21 /* Can also use index to insert before - uncomment this */
22 // ul1.insertBefore(new_li, list[0])
23
24 /* Can also do - uncomment this */
25 // ul1.insertBefore(new_li, ul1.firstChild);
26
27 /* To remove an element - uncomment this */
28 // list[0].remove();
29
30 /* OR - uncomment this */
31 // ul1.removeChild(ul1.children[1]);
32
33 /* To replace an element - uncomment this */
34 // list[0].parentNode.replaceChild(new_li, ul1.children[2]);
35 }
Append to end
2.0 Events
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Events</title>
7
8 <script type="text/javascript" src="2-js-events.js">
9
10 </script>
11 </head>
12
13 <body onload="init()">
14
15 <div>
16 <!-- Add in HTML -->
17 <p onclick="handler(event)">Popular games</p>
18 <ul>
19 <li>Call of Duty</li>
20 <li>Fortnite</li>
21 <li>PUBG</li>
22 </ul>
23 </div>
24
25 </body>
26 </html>
Event Property
Callback function
Can also be an anonymous function
1 function init() {
2 list = document.querySelectorAll("li");
3
4 for (let i in list) {
5 list[i].onclick = handler;
6 }
7
8 console.log(document.body.children[0].children[0].onclick);
9 }
10
11 function handler(event) {
12 // For when parameters are not passed - depends on browser
13 ev = event || window.event;
14 console.log(ev.target.innerHTML);
15 ev.target.style.color = "blue";
16 ev.preventDefault();
17 }
Event Listener
An event listener watches for an event on an element
element.addEventListener(event, handler)
1 function init() {
2 list = document.querySelectorAll("li");
3
4 document.querySelector("p").addEventListener("click", function(event)
{
5 event.target.style.color = 'green';
6 event.target.innerHTML = "I was clicked";
7 })
8
9 console.log(document.body.children[0].children[0].onclick);
10 }
11
12 function handler(event) {
13 // For when parameters are not passed - depends on browser
14 ev = event || window.event;
15 console.log(ev.target.innerHTML);
16 ev.target.style.color = "blue";
17 ev.preventDefault();
18 }
Event Bubbling
In the event bubbling model, the click event first occurs on the element that was clicked
The click event then goes up the DOM tree, firing on each node along its way until it reaches
the document object
Event Capturing
In the event capturing model, an event starts at the least specific element and flows
downward toward the most specific element (element that was clicked)
The three phases in which an event can propagate to handlers defined in parent elements
are
Capturing phase
Target phase
Bubbling phase
element.addEventListener("event", func_ref, flag);
if flag = true , handler registered for capturing phase
Example
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Event Propagation</title>
7
8 <script type="text/javascript" src="3-event-prop.js">
9
10 </script>
11 </head>
12
13 <body onload="init()">
14
15 <div id='div'>
16
17 <!-- Click event propagates from div to li -->
18 <p onclick="handler(event)">Popular games</p>
19 <ul id='ul'>
20 <li id='li'>Call of Duty</li>
21 <li>Fortnite</li>
22 <li>PUBG</li>
23 </ul>
24 </div>
25
26 </body>
27 </html>
1 /*
2 Capturing phase, Bubbling phase, Target phase
3
4 div -> p -> ul -> li
5 */
6
7 function init() {
8 // false by default (bubbling)
9
10 // Will be called first - true for capturing phase
11 document.querySelector("#div").addEventListener("click", handler,
true);
12 document.querySelector("#ul").addEventListener("click", handler,
true);
13
14 // target - true or false
15 document.querySelector("#li").addEventListener("click", handler,
true);
16
17 // called in the end - false for bubbling
18 document.querySelector("#div").addEventListener("click", handler,
false);
19 document.querySelector("#ul").addEventListener("click", handler,
false);
20
21 // target - true or false
22 document.querySelector("#li").addEventListener("click", handler,
false);
23
24 }
25
26 function handler(event) {
27 // event.eventPhase -> 0, 1 or 2
28 console.log(event.eventPhase + ' ' + event.target.id + ' ' +
event.currentTarget.id);
29 // event.stopPropagation();
30 // event.cancelBubble = true;
31 }
XML
1 <empinfo>
2 <employees>
3 <employee>
4 <name>Daenerys Targaryen</name>
5 <age>17</age>
6 </employee>
7 <employee>
8 <name>Jon Snow</name>
9 <age>20</age>
10 </employee>
11 <employee>
12 <name>Robert Baratheon</name>
13 <age>46</age>
14 </employee>
15 </employees>
16 </empinfo>
JSON
1 {
2 "empinfo": {
3 "employees": [
4 {
5 "name": "Daenerys Targaryen",
6 "age": 17
7 },
8 {
9 "name": "Jon Snow",
10 "age": 20
11 },
12 {
13 "name": "Robert Baratheon",
14 "age": 46
15 }
16 ]
17 }
18 }
XML
Converting to Object Hierarchy
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>XML and JSON</title>
7 </head>
8 <body>
9 <h1>XML and JSON</h1>
10 <p id="xml-demo"></p>
11 <script src="4-xml-json.js">
12 </script>
13 </body>
14 </html>
1 var xmlText;
2
3 xmlText = "<bookstore>" +
4 "<book>" +
5 "<title>Everyday Italian</title>" +
6 "<author>Giada Laurentiis</author>" +
7 "<year>2005</year>" +
8 "</book>" +
9 "</bookstore>";
10
11 /* Convert to object hierarchy - DOM parser */
12
13 var parser = new DOMParser();
14
15 /* Convert string to object hierarchy */
16 xmlDOM = parser.parseFromString(xmlText, "text/xml");
17 xmlTitle = xmlDOM.getElementsByTagName("title")[0];
18 xmlTitle.childNodes[0].nodeValue += " - Modified";
19
20 document.getElementById("xml-demo").innerText =
xmlTitle.childNodes[0].nodeValue;
21
22 /* Convert object hierarchy to string - serializer for req/res */
23 var xmlTextSerializer = new XMLSerializer();
24 xmlString = xmlTextSerializer.serializeToString(xmlDOM);
25
26 console.log(xmlString);
Simple Server
Note: to start a simple server using python, run the following command (Terminal on Mac,
Command Prompt on Windows)
By default, it opens on port 8000
Go to http://localhost:8000 to find the files on the server
1 python -m http.server
Output
Rendered in a browser
Console
JSON
Converting to Object Hierarchy
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>XML and JSON</title>
7 </head>
8 <body>
9 <h1>XML and JSON</h1>
10 <p id="json-demo-1"></p>
11 <p id="json-demo-2"></p>
12 <script src="4-xml-json.js">
13 </script>
14 </body>
15 </html>
1 // JSON text always uses double quotes for the keys and
2 // values, not single quotes
3 var jsonText;
4 jsonText = '{"name": "Thor Ragnarok", "cast": ["Chris Hemsworth", "Tom
Hiddleston"]}';
5
6 // Using JSON.parse() to convert string to obj
7 jsonObj = JSON.parse(jsonText);
8 document.querySelector("#json-demo-1").innerText = jsonObj.name;
9
10 console.log(jsonObj.cast)
11 jsonObj.year = 2017;
12 jsonObj.rating = 7.8;
13
14 // Using JSON.stringify() to convery obj to string
15
16 var newJsonStr = JSON.stringify(jsonObj);
17 document.querySelector("#json-demo-2").innerText = newJsonStr;
18
19 // jsonObj.toString() -> can be sent to server
Output
Rendered in a browser
Console
5.0 HTML 5
New input types and properties
HTML5 has added a little meaning (semantic) and identifiers to its elements, so web
developers can use them wisely in their web pages
placeholder
required
pattern
autofocus
New structural HTML5 tags
Basic HTML5 Document
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>HTML Tags</title>
7 </head>
8 <body>
9 <!-- Semantic tags - easier for
10 programs/humans to understand-->
11 <header>
12 <h1>Logo Here</h1>
13 </header>
14
15 <nav><ul>
16 <li>Link 1</li>
17 <li>Link 2</li>
18 <li>Link 3</li>
19 </ul></nav>
20
21 <article>
22 <section></section>
23 </article>
24
25 </body>
26 </html>
Input tags
tel for telephone numbers
Placeholders, regex, name
Color pickers
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>HTML5 Inputs</title>
7 <script>
8 function setText() {
9 let col = document.querySelector("#colcode").value;
10 document.querySelector("#coltext").value = col;
11 }
12
13 function setColor() {
14 let text = document.querySelector("#coltext").value;
15 document.querySelector("#colcode").value = text;
16 }
17 </script>
18 </head>
19 <body>
20 <form action="save.py" method="GET">
21 <!-- Placeholders, required, regex, name -->
22
23 <!-- Telephone number -->
24
25 <input type="tel" autofocus required placeholder="xxx-xxx-xxxx"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" name="tel"></input>
26
27 <!-- Color picker -->
28 <input id="colcode" onchange="setText()" type="color"
name="ucolor"></input>
29
30 <!-- Text element -->
31 <input id="coltext" onchange="setColor()" type="text"
id="coltext"></input>
32 <button type="submit">Submit</button>
33 </form>
34 </body>
35 </html>
Color picker
Audio
Standard src - use .ogg and .mp3
Avoid unnecessary download, use <source/> tags, instead of putting under <audio>
</audio> tags
<source src="song.mp3" type="audio/mp3"/>
Default message for no support
1 <audio preload controls="controls">
2 <source src="audio/Flip.mp3" type="audio/mp3"/>
3 </audio>
Video
Standard src - .ogg, .mp4 and webm
Use <video></video> and <source/> tags
Controls for pause, play
Default message
width, height
Progress
Progress bar for task completion (no need extensive JS and CSS)
1 <label for="prog">Progress</label>
2 <progress id="prog" value="0" max="100"></progress>
Canvas
Uses JavaScript to draw graphics on a web page
Rectangular area of specified dimensions
Syntax
All drawing must be done inside a JavaScript using the context object
Code Implementation
HTML file
1 <!DOCTYPE html>
2 <html lang="en">
3
4 <head>
5 <meta charset="UTF-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <title>Canvas and SVG</title>
8 <!-- Canvas, Scalable vector graphics (can zoom) -->
9
10 <script type="text/javascript" src="8-canvas-svg.js"></script>
11 </head>
12 <body onload="init()">
13 <canvas id="c1" width="400px" height="200px">
14 No canvas support
15 </canvas>
16 </body>
17
18 </html>
JS file
1 function init() {
2 c1 = document.querySelector("#c1");
3
4 /* Context object for 2D animation */
5 ctx = c1.getContext("2d");
6
7 ctx.fillStyle = "#FF0000";
8
9 // Syntax
10 // ctx.arc(centerx, centery, radius, startangle, endangle, direction);
11
12 // Clockwise semicircle
13 // ctx.arc(100, 100, 80, 0, Math.PI, 0);
14 // Anticlockwise semicircle
15 // ctx.arc(100, 100, 80, 0, Math.PI, 1);
16
17 ctx.arc(100, 100, 80, 0, 2*Math.PI, 0);
18 ctx.fill();
19
20 // For stroking, no filling
21 // ctx.strokeStyle = "#FF0000";
22 // ctx.rect(100, 100, 100, 100);
23 // ctx.stroke();
24 }
Rendered in a browser
SVG
Scalable Vector Graphics
Vector-based graphics using HTML elements
Do not lose any quality if they are zoomed or resized
Syntax
Circle
Ellipse
Polygon
Text
7.0 Geolocation
The Geolocation API of HTML5 helps in identifying the user’s location
Only if user grants permission
Accessed via JavaScript, through the navigator.geolocation object
Methods
getCurrentPosition(success_callback [, error_callback, geo_loc_options])
watchPosition(success_callback [, error_callback, geo_loc_options])
Associated Objects
Success callback function receives position object with these read only properties: double
latitude, longitude, accuracy, altitude, altitudeAccuracy, heading
(direction), speed
Error callback function receives error object with these two properties:
short code
1 - PERMISSION_DENIED
2 - POSITION_UNAVAILABLE
3 - TIMEOUT
DOMString message
JavaScript
1 function getPos() {
2 navigator.geolocation.getCurrentPosition(show, error);
3 }
4
5 function show(position) {
6 // Global for console
7 ps = position;
8 console.log("Current position: " + position.coords.latitude + " " +
position.coords.longitude);
9 }
10
11 function error(error) {
12 console.log(error);
13 }
HTML
1 <body onload="getPos()">
2 <button onclick="getPos()">Get current position</button>
3 </body>
Rendered in browser (only Chrome seemed to work for me; Firefox and Safari failed)
Implementation
A new Worker object in the main page must be created. The constructor takes the name of
the worker script (eg: my-worker.js )
If the specified file exists, the browser will spawn a new worker thread, which is downloaded
asynchronously
The worker will not begin until the file has completely downloaded and executed
If the path to the file returns 404 , it will fail silently
Message Passing
Main JS file
Rendered in a browser
9.0 jQuery
JavaScript library that simplifies DOM manipulation and JS programming
Basic syntax for selecting
1 $(selector).action()
JavaScript vs jQuery
JavaScript
1 document.getElementById('textbox').style.display = 'none';
jQuery
1 $('#textbox').hide();
JavaScript
1 var h1 = document.CreateElement("h1");
2 h1.innerHTML = "my text";
3 document.getElementsByTagName('body')[0].appendChild(h1);
jQuery
1 $(body).append($("<h1/>").html("my text")) ;
Code Example
Body of HTML
1 <body>
2 <p>Games</p>
3 <ul>
4 <li>Call of Duty</li>
5 <li class="g1">Fortnite</li>
6 <li class="g1">PUBG</li>
7 </ul>
8 </body>
jQuery inside the jQuery tags
Rendered in browser
Cascading
Chaining Methods, also known as Cascading, refers to repeatedly calling one method after
another on an object, in one continuous line of code
Example 1
1 $("#wrapper").fadeOut().html("Welcome, Sir").fadeIn();
Example 2
1 str.replace("k", "R").toUpperCase().substr(0,4);
Events
Register an event handler in one of two ways
1 $("span#message").click(function(event) {});
Without the function reference argument, the event methods are treated like a manual firing
of event
1 $("span#message").click();
Code Example
Within any event handler function this element refers to the element for which the handler
is called
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0"
/>
6 <title>jQuery Events</title>
7 <script
8 type="text/javascript"
9 src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
10 </script>
11 <script>
12 $(document).ready(function () {
13 // also $('p').on('click', function()) - multiple
14 $('p').click(function () {
15 $(this).css('color', 'green').html('I was clicked');
16 });
17
18 $('p').mouseover(function() {
19 // $('ul').slideToggle('slow');
20 // $('button').toggle().html('hidden');
21 if ($('button').attr('visible')) {
22 $('button').show().html('hidden');
23 }
24 else {
25 $('button').hide().html('click');
26 }
27 })
28
29 // animate
30 $('li.g1').click(function() {
31 if ($(this).css('opacity') == 1) {
32 $(this).animate({
33 left: '100px',
34 opacity: 0.4,
35 fontSize: '3em'
36 }, 1000);
37 }
38 else {
39 $(this).animate({
40 left: '0px',
41 opacity: 1,
42 fontSize: '1em'
43 }, 1000);
44 }
45 })
46 });
47 </script>
48 </head>
49 <body>
50 <!-- More than one event; chaining -->
51 <p>Games</p>
52 <ul>
53 <li>Call of Duty</li>
54 <li class="g1">Fortnite</li>
55 <li class="g1">PUBG</li>
56 </ul>
57 <button>Click</button>
58 </body>
59 </html>
60
Rendered in browser
Lots of animation/styling effects can be accomplished using the effects methods like hide,
show, toggle, fadein, fadeout etc (read docs)
Promises
jQuery
A promise is used to handle the asynchronous result of an operation
With Promises, we can defer execution of a code block until an async request is completed
The primary way of interacting with a promise is through its then method, which registers
callbacks to receive either a promise’s eventual value or the reason why the promise cannot
be fulfilled
The then() method accepts two functions: one to execute in the event that the promise is
fulfilled and the other if the promise is rejected
If a promise is neither fulfilled nor rejected (for example, still waiting for the response of a
server calculation), it’s pending
A promise may be in one of the three states: unfulfilled, fulfilled, and failed
The promise may only move from unfulfilled to fulfilled, or unfulfilled to failed
Code Example
1 /*
2 1. Callbacks - function refs accepted as argument, asynchronous
3 2. Promises - used to handle async result of
4 operation (conditonal execution of callbacks)
5 */
6
7 var weather;
8 const date = new Promise(
9
10 // Attach a callback based on then and catch
11 function(resolve, reject) {
12 // Usually an API call - with delay
13 setTimeout(function () {
14 weather = true;
15
16 if (weather) {
17 const dateDetails = {
18 name: 'Cuban Restaurant',
19 location: '55 Street',
20 table: 5
21 };
22 resolve(dateDetails);
23 } else {
24 reject(new Error('Bad weather'));
25 }
26 }, 2000);
27 }
28 )
29
30 // Status will be resolved or rejected, or pending
31 date
32 .then(function(details) {
33 console.log('We are going on a date');
34 console.log(details);
35 })
36 .catch(function(error) {
37 console.log(error.message);
38 })
Console
AJAX
Using XHR or XMLHTTPRequest
0 - uninitialized
1 - loading
2 - response headers received
3 - some response body received
4 - request complete
status - HTTP status code
Code Example
Needs to be run on a local server (how to setup a simple Python server)
Note: simple http server doesn't support POST methods
JavaScript
1 function loadData() {
2 let xhr = new XMLHttpRequest();
3
4 // true - asynchronous
5 xhr.open("get", "sample.txt", true);
6 xhr.onreadystatechange = showData;
7 // Default - text
8 xhr.responseType = 'text';
9 xhr.send(null);
10 }
11
12 function showData() {
13 // this refers to xhr object
14 if (this.readyState == 4 && this.status == 200) {
15 // this.response or responseText or responseXML
16 document.querySelector('#container').innerHTML =
this.responseText;
17 }
18 }
HTML
sample.txt
Syntax
1 $.ajax({name:value, name:value})
Code Example
1 function getData() {
2 $.ajax({
3 url: 'sample.txt',
4 method: 'get',
5 success: function (result) {
6 $("#container").html(result);
7 },
8 error: function (xhr, textstatus, errMsg) {
9 console.log("Error: " + errMsg);
10 }
11 })
12 }
Fetch Method