JavaScript

Live Demo: https://www.youtube.com/watch?v=BrQKM_uaZKE

Github Repo: https://github.com/web-engineering-tuwien/recipe-search-live-demo

https://javascript.info/

https://developer.mozilla.org/en-US/docs/Web/Tutorials#javascript-tutorials

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures

https://eloquentjavascript.net/


JavaScript

interpreted scripting language.

Standardized as ECMAScript language in the ECMA-262

Other ECMAScript implementations: JScript, ActionScript, QtScript, …

In this course: EXMAScript 6

Embedding into HTML

External

linking to an external JavaScript file in <head>

defer = asynchronous loading

It will defer (= delay) loading the JS until the page load is completed.

<script type="text/javascript" src="foo.js" defer> </script>

Internal

In <body> or <head>

type="module" is defer by default

<script type="module">
statement;
statement;
...
</script>
<script type="text/javascript">
statement;
statement;
...
</script>

As event handlers

<a href="http://www.bar.com" onmouseover="alert('hi');">

Pseudo-URLs in links

<a href="javascript:alert('You clicked');">Click me</a>

Syntax

Inheritance

Browser and Document APIs

Standard Library/Common APIs

Overview

Overview: There’s a root object called window.

APIs accessible through Javascript.

Browser Object Model BOM → interact with browser

Window,Frames,History,Location,Navigator (browser type & version), ...

Storage (Local Storage, Cookies)

Document Object Model DOM → interact with HTML page

Properties: document.forms,document.links , …

Methods: document.createElement,document.getElementsByTagName , …

Browser Object Model BOM (window)

Allows access to browser objects. → Not standardized but very similar in most browsers.

Object Property and Methods


window Other global objects, open(), close(), moveTo(), resizeTo()

screen width, height, colorDepth, pixelDepth, …

location hostname, pathname, port, protocol, assign(), …

history back(), forward()

navigator userAgent, platform, systemLanguage, …

document body, forms, write(), close(), getElementById(), …

Popup Boxes alert(), confirm(), prompt()

Timing setInterval(func,time,p1,…), setTimeout(func,time)

Storage (Local Storage, Cookies)

Cookies

Cookies are sent with every single request.

String/value pairs, Semicolon separated.

document.cookie	=	"name=Jane Doe; nr=1234567;	expires=" + date.toGMTString()

Web Storage

Data that the user is required to store (as key / value pairs)

Browser defines storage quota.

Both storage objects provide same methods and properties:

  • setItem(key, value) – store key/value pair.
  • getItem(key) – get the value by key.
  • removeItem(key) – remove the key with its value.
  • clear() – delete everything.
  • key(index) – get the key on a given position.
  • length – the number of stored items.

  1. Local Storage(window.localStorage)

    stored in users browser without any expiration date.

    In comparison to Cookies: more secure, larger, not transferred (stays local)

  1. Session Storage(window.sessionStorage)

    Data is destroyed when tab/browser is closed.

Document Object Model DOM

For HTML, XHTML, XML

HTML elements as objects with properties, methods and events - DOM tree nodes.

The document object is the trees root.

Everything in the html file becomes a node:

text nodes (spaces and \n are stored as seperate nodes), comment nodes ...

Getting nodes

ID, tag name, class name, Document properties

let	title	=	document.getElementById("title");
let	links	=	document.getElementsByTagName("a");
let	greens	=	document.getElementsByClassName("green");
let	imgs	=	document.images;
let	firstParaBox	=	document.querySelector(“p.box”);
let	allBoxes	=	document.querySelectorAll(“p.box,div.box”);

Reading properties

<UL id="t1">
<LI>Item 1</LI>
</UL>
document.getElementById('t1').nodeName
// -> returns 'UL'
document.getElementById('t1').getAttribute('id')
// -> returns 't1'
document.getElementById('t1').innerHTML
// -> returns '<li>Item 1</li>'
document.getElementById('t1').children[0].nodeName
// -> returns 'LI'
document.getElementById('t1').children[0].innerText
// -> returns 'Item 1'

Manipulating nodes

  • Content (innerHTML)
  • Element attributes
  • Element style
  • Element class ( className , classList )
title.innerHTML	= "newTitle";
links[0].href	= "http://...";
links[0].setAttribute("href",…)
greens[0].style.color	= “red";
greens[0].className	=	“red"
greens[0].classList.add(“dangerzone”)

Adding nodes

Create, append, remove, …

let	header	=	document.createElement("h2");
let	text	=	document.createTextNode("SubTitle");
header.appendChild(text);
document.removeChild(title);
document.replaceChild(title, header);

Adding Event Handlers

let list = document.getElementById('t1');
list.addEventListener('click', (event) => {
alert(`Clicked: ${event.target.innerText}`);
});

Traversal of nodes

parentElement, nextElementSibling, previousElementSibling, childNodes

Accessibility

DOM Updates

Changing / updating the DOM frequently

can confuse screen readers

not be visible in high magnification

Updates may come too fast

Guidelines - Accessible Rich Internet Applications (ARIA)

If the content updates more than 5 seconds, provide ability to pause, stop, or hide them

Inform users of changes: Setting focus, Highlight, Alert, Live Region (ARIA Term)

Communicate to user that page is dynamic

Provide static HTML page alternatives

Event-Driven Programming

<img src="..." alt="..." onclick="alert('Hello');" />
let	button = document.getElementsByTagName("button")[0]
header.click();	//Execute	predefined event
header.onclick = function(){alert('Clicked!');}	//Set	event	listenerlet	func = function() {alert('Clicked!');}
header.addEventListener("click", func);
header.removeEventListener("click",	func);

DOM Event Types

Event Description


load,unload User enters/leaves page

change Form input field changes

focus/blur User focuses/unfocuses an input field

Submit Form is submitted

mouseover, mouseout Mouse enters/leaves region

mousedown/mouseup/click Mouse click events

keydown/keyup/keypress Keyboard events

drag User drags an element

Asynchronous Programming

Asynchronous Programming ≠ Multithreading

Waiting for actions to finish is implicit in the synchronous model, while it is explicit, under our control, in the asynchronous one.

Sending Asynchronous Requests with Callbacks and Promises (like HTTP Fetch)