13. JavaScript
13. JavaScript
Web Programming
Topics
Objects
Arrays
DOM/BOM
Javascript Events
Objects
Objects are used to store keyed collections of various data and complex
entities
An object can be created with curly brackets {…} with an optional list of
properties
let user = {
name: "Aster",
age: 22,
};
A property has a key (also known as “name” or “identifier”) before the colon
":" and a value to the right of it
Properties
We can add, remove and read properties
delete user.age;
Properties
We can also use multiword property names, but then they must be quoted
let user = {
name: "Aster",
age: 22,
"likes coffee": true,
};
Square Brackets
For multiword properties, the dot access doesn’t work
contains no spaces, doesn’t start with a digit and doesn’t include special
characters ($ and _ are allowed)
Square Brackets
Square Bracket notation works with multi-word properties
let user = {
name: "Aster",
age: 22,
};
let salaries = {
Kebede: 100,
Aster: 160,
Kedir: 130,
};
Exercise
Create a function multiplyNumeric(obj) that multiplies all numeric
property values of obj by 2
multiplyNumeric(menu);
alert(user.name);
Comparison by Reference
Two objects are equal only if they are the same object.
let a = {};
let b = a; // copy the reference
alert( a == b ); // true,
alert( a === b ); // true
Comparison by Reference
Two independent objects are not equal
let a = {};
let b = {}; // two independent objects
alert( a == b ); // false
Arrays
There are two syntaxes for creating an empty array:
alert( fruits.length ); // 3
Arrays
An array can store elements of any type
// mix of values
let arr = [ 'Apple', { name: 'Aster' }, true, function() {
alert('hello'); } ];
// get the object at index 1 and then show its name
alert( arr[1].name ); // Aster
// get the function at index 3 and run it
arr[3](); // hello
Methods pop/push, shift/unshift
A queue is one of the most common uses of an array which supports two
operations:
fruits.push("Pear");
fruits.unshift('Apple');
fruits.push("Orange", "Peach");
fruits.unshift("Pineapple", "Lemon");
The for..of doesn’t give access to the index of the current element, just its
value
let arr = ["Apple", "Orange", "Pear"];
It is actually not the count of values in the array, but the greatest numeric
index plus one
// what's in fruits?
alert( fruits.length ); // ?
Exercise
Create an array styles with items “Jazz” and “Blues”
Append “Rock-n-Roll” to the end
Replace the value in the middle by “Classics”
Your code for finding the middle value should work for any arrays with
odd length
Strip off the first value of the array and show it
Prepend Rap and Reggae to the array
Exercise
Write the function sumInput() that:
Asks the user for values using prompt and stores the values in the array
// 📁 main.js
import { sayHi } from "./sayHi.js";
alert(sayHi); // function...
sayHi("Aster"); // Hello, Aster!
Browser Environment
There’s a global object
called window
Browser Environment
There’s a “root” object
called window
2. it represents the
“browser window” and
provides methods to
control it
window
As a global object
function sayHi() {
alert("Hello");
}
All of the JavaScript code (except code running in worker threads) running
in that window shares this single global object
the parseInt() function, the Math object, the Set class, and so on
The Global Object in Web Browsers
In web browsers, the global object also contains the main entry points of
various web APIs
The Global Object in Web Browsers
One of the properties of the global object is named window, and its value is
the global object itself
This means that you can simply type window to refer to the global object
in your client-side code
Browser Object Model (BOM)
Represents additional objects provided by the browser (host environment)
For Example:
The location object allows us to read the current URL and can redirect
the browser to a new one
Browser Object Model (BOM)
Represents additional objects provided by the browser (host environment)
The API for working with HTML documents is known as the Document Object
Model, or DOM
Document Object Model (DOM)
<html>
<head>
<title>Sample Document</title>
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>simple</i> document.</p>
</body>
</html>
Document Object Model (DOM)
Document Object Model (DOM)
The DOM API mirrors the tree structure of an HTML document
there are also methods for moving elements within the document and
for removing them
Document Object Model (DOM)
There is a JavaScript class corresponding to each HTML tag type
The initial value of the src property is the attribute value that appears in
the HTML tag, and setting this property with JavaScript changes the value
of the HTML attribute (and causes the browser to load and display a new
image)
Document Object Model (DOM)
The document object is the main “entry point” to the page
<html> =
document.documentElement
Walking the DOM
All operations on the DOM start
with the document object
<html> = document.documentElement
<body> = document.body
<head> = document.head
Walking the DOM
Children: childNodes, firstChild, lastChild
Descendants – all elements that are nested in the given one, including
children, their children and so on
<html>
<body>
<div>Begin</div>
<ul>
<li>Information</li>
</ul>
<div>End</div>
...more stuff... example.js
<script src="example.js"></script>
</body>
let children = document.body.childNodes;
</html>
for (let i = 0; i < children.length; i++) {
alert(children[i]);
}
Walking the DOM
Children: childNodes, firstChild, lastChild
Properties firstChild and lastChild give direct access to the first and
last children
For instance, in childNodes we can see both text nodes, element nodes, and
even comment nodes if they exist
If you want to manipulate element nodes that represent tags and form the
structure of the page, you can use element-only navigation
Walking the DOM
Element-Only Navigation
Walking the DOM
Element-Only Navigation
tr.cells – the collection of <td> and <th> cells inside the given <tr>
Method Search By
querySelector() CSS-selector
querySelectorAll() CSS-selector
getElementById() id
getElementsByName() name
getElementsByTagName() tag or *
getElementsByClassName() class
Node Properties
Each DOM node belongs to
a certain class
1 for elements,
3 for text nodes, and a few others for other node types
It is read-only
Main Node Properties
nodeName/tagName
It is read-only
Main Node Properties
innerHTML
Can be modified
Main Node Properties
outerHTML
Can be modified
Main Node Properties
textContent
Writing into it puts the text inside the element, with all special characters
and tags treated exactly as text
Can safely insert user-generated text and protect from unwanted HTML
insertions
Main Node Properties
hidden
All DOM nodes generate such signals (but events are not limited to DOM)
DOM Events
Mouse Events
For instance, to assign a click handler for an input, we can use onclick,
like here
elem.onclick = function () {
alert("Thank you");
};
In the code below the button shows its contents using this.innerHTML
● use CSS to remove the default border around the input box and to add
a new border around the container div
Web Components
What else do you need to do to make the search box functional
● use JavaScript to register event handler to handle the click events for
the magnifying and cancel icons
Web Components
Most frontend frameworks such as React and Angular support the creation
of reusable user interface components like the search box
To use a web component, just use its tag in your HTML file
<search-box>
<img src="images/search-icon.png" slot="left" />
<img src="images/cancel-icon.png" slot="right" />
</search-box>
Browser Features of Web Components
The three web browser features that allow us to implement web components
HTML Templates
Custom Elements
Shadow DOM
Networking
Every time you load a web page, the browser makes network requests—using
the HTTP and HTTPS protocols—for an HTML file as well as the images, fonts,
scripts, and stylesheets that the file depends on
As with Server-Sent Events, the client must establish the connection, but once
the connection is established, the server can asynchronously send messages
to the client
Unlike SSE, binary messages are supported, and messages can be sent in both
directions, not just from server to client
References
The Modern JavaScript Tutorial