We take developers from good to great

WE ARE THE JSLEAGUE

Intro to Web
HTML+CSS+JS


Whoami
Diana Miron
10 years experience as front-end dev
CEO JSLeague & JSKids
UI/UX & web animations enthusiast


JSLeague


Whoareyou
Let's get to know each other
- intro
- expectations
- future plans with Web

Agenda
Day 1
- Intro to Web: HTML + CSS + JS
- Practice in Codepen
- My first web page
Day 2
- Website components with Bootstrap
- CSS Modern Layouting with Flexbox
- Adding JS
Day 3
- Intro to JavaScript
- Website functionalities with JS

Materials
Exercises
- https://git.jsleague.ro/dee/intro-web-dec-2021
Slides
- shorturl.at/lEQV7

2x 15' coffee break + 1h lunch break
We expect cooperation from all participants to help ensure a safe environment for everybody.
We treat everyone with respect, we refrain from using offensive language and imagery, and we encourage to report any derogatory or offensive behavior to a member of the JSLeague community.
We provide a fantastic environment for everyone to learn and share skills regardless of gender, gender identity and expression, age, sexual orientation, disability, physical appearance, body size, race, ethnicity, religion (or lack thereof), or technology choices.
We value your attendance and your participation in the JSLeague community and expect everyone to accord to the community Code of Conduct at all JSLeague workshops and other events.

Code of conduct

90's kids will remember
Web history
A short history of web π©π»βπ»

Web history


- The World Wide Web was invented by Tim Berners-Lee and developed at CERN in 1989-1990
- The first web browser was released to the public on August 1991


The first web page

First browsers



1993 - Mosaic browser - first commercial browser
1995 - Netscape and Internet Explorer



Early days

Second generation websites





Table based layouts

Table based layouts

Spacer gif


Web timeline
- 1991 - HTML
- 1994 - HTML 2
- 1996 - CSS 1 + Javascript
- 1997 - HTML 4
- 1998 - CSS 2
- 2000 - XHTML 1
- 2002 - Tableless Web design
- 2005 - AJAX
- 2009 - HTML 5
- 2012 - CSS 3
- 2016 - AngularJS first release

New generation websites


New generation websites

Today

1.86 billion websites

The website trio
Introduction to HTML
HTML + CSS + JS = π

The Mighty Trio


HTML + CSS + JS
HTML = Hyper Text Markup Language
CSS = Casscading Style Sheets
JS = JavaScript
JavaScript != Java

HTML + CSS + JS


Process


Front-end vs. Back-end

Front-end
HTML + CSS + JS
Back-end
Java, C#, Objective-C, Python
Scala, Go Lang etc
700 programming languages https://en.wikipedia.org/wiki/List_of_programming_language

Code


Text editors


Text editors


What web is made of
Web page structure
Sugar, spice and everything nice π

HTML
- HTML = Hyper Text Markup Language
- is a mark-up language
- can be used by anyone
- can be written in a variety of text editors (Notepad, Notepad ++, Sublime, Atom etc.)
- can be processed by a variety of devices (computer, mobile phone, tablet etc).

HTML
- All HTML code is made up of tags
- These are two-fold:
- pair (close)
- unpaired (no need to be closed)
- tag names are case-insensitive
<p> My name is Diana </p>
opening tag
closing tag
content

HTML
<html>
<head>
<title> Prima mea pagina </title>
</head>
<body>
<div>
<p>>Hello, there!</p>
</div>
</body>
</html>

HTML


Tags
Primary tags
Tag, you're it! π

HEAD
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1,
shrink-to-fit=no, minimum-scale=1">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=
Open+Sans:300,400,600,700&lang=en" />
<link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet">
<link rel="stylesheet" href="stylesheet.css">
<script type="text/javascript" src="script.js"></script>
<title>My First Hero App</title>
</head>

Types of tags
<section></section>
<header></header>
<footer></footer>
<aside></aside>
<div></div>
<p></p>
<h1></h1> .... <h6></h6>
<span></span>
<small></small>
<form></form>
<input/>
<select></select>
<button></button>
<ul></ul>
<ol></ol>
<table></table>
<a></a>
<img/>
<hr/>
<br/>

Semantic elements
- header
- nav
- main
- section
- article
- aside
- footer
- figure


Attributes
<div id="container"> ... </div>
<p class="details"> ... </div>
<a href="http://example.com"> link </a>
<input type="checkbox" checked>
<button disabled> Click </button>

Block vs. Inline elements



Lists
- Unordered list
<ul>
<li>Item 1</li>
<li>Item 2</li>
...
</ul>
- Ordered list
<ol>
<li>Item 1</li>
<li>Item 2</li>
...
</ol>



Images, video, links
- Images
<img src="image.png" alt="What the picture is about">
- Anchors
<a href="http://example.com" target="_blank">link</a>
- Video
<video controls width="250" height="300" src="vide.mp4">
Video not supported
</video>

Tables - Deprecated
<table border>
<thead>
<tr>
<th colspan="2">The table header</th>
</tr>
</thead>
<tbody>
<tr>
<td>row 1 column 1</td>
<td>row 1 column 2</td>
</tr>
</tbody>
</table>

Forms
<form action="script.php" method="POST">
<label for="name"> user name: </label>
<input type="text" name="user-name" id="name">
<label for="user-password" id="password"> password </label>
<input type="password" name="user-password" id="password">
<label for="remember"> Remember me </label>
<input type="checkbox" name="remember-me" id="remember" checked>
<input type="submit" value="Log in">
</form>

Exercise
Let's write some tags π»

CSS: Ids, classes and selectors, attributes
CSS
The pretty part π

Intro
CSS (Cascading Style Sheets) is a declarative language that controls how web pages look in the browser.
- a set of rules that describe the visual properties of elements look on a page; rules are organized in stylesheets
- the rules are targeted to DOM elements through selectors
- the style cascade and specificity decides which rules apply when multiple selectors match an element

Intro

CSS Rules


Selectors
- tag
- class
- id
div {
color: red;
}
#main {
color: red;
}
p {
color: red;
}
.content {
color: red;
}
.green {
color: green;
}

ID vs Class
Ids are unique:
- relationship 1-1
- an item can have a single id
- an id with a given name can be used for a single element
- identified by #
Classes are not unique:
- multi-many relationship
- an element can have as many classes as possible
- the name of a class can be used for as many items as possible
- identified by dot

ID vs Class
<img class="hero--image img-green red"
id="hero-diana"
src="img/Doctor_Strange.jpg" />
HTML
CSS
.hero--image {
border: none;
}
.red {
color: red;
}
#hero-diana {
background: pink;
}

Syntax
.hero {
width: 70%;
min-width: 900px;
position: absolute;
left: 15%;
top: 115px;
will-change: auto;
transition: left .45s ease-out;
}

Nesting selectors
.myList li {
color: red
}
<ul class="myList">
<li>Colored element</li>
</ul>
<ol>
<li>element</li>
<ol>


Implementation
1. External file as link
<head>
<link rel="stylesheet" href="stylesheet.css">
</head>
2. Internal style - in HEAD
<head>
<style>
.red {
color: red;
}
</style>
</head>
3. Inline - as element attribute
<h1 style="color: red;" class="red">I am a green text</h1>

Specificity


Specificity
h1 {
color: red;
}
.headline {
color: blue;
}
#myText {
color: green
}
<h1 class="headline">Title 1</h1>
<h1 class="headline" id="myText">Title 2</h1>


!important
.myClass {
color: red !important;
}
#special {
color: blue;
}
<p class="myClass">
Some text goes here
</p>
<p class="myClass" id="special">
Some other text
</p>


Pseudo-classes
button:hover {
color: blue;
}
li:first-child {
color: blue;
}
li:nth-child(3){
color: blue;
}
li:nth-child(even){
color: blue;
}
li:not(.red) {
color: blue;
}

Text
p {
color: red;
font-family: Arial;
/* font-family: "Courier New"; */
font-size: 24px;
font-weight: bold;
/* font-weight: 700; */
}

Text
div {
text-align: center; /* left | right */
}


Text
div {
text-align: center; /* left | right */
}


Color
- text-color
p {
color: red;
}
- background-color
p {
background-color: red;
}


Color
- Hexadecimal
p {
color: #0000FF; /* blue */
}
- RGB(A)
p {
color: rgb(0,0,255); /* blue */
color: rgba(0,0,255, 0.5);
/* blue + 0.5 transaprency */
}



Color
- HSL (Hue-Saturation-Light)
p {
color: hsl(240, 100%, 50%);
/* blue */
color: hsla(240, 100%, 50%);
/* blue + 0.5 transaprency */
}

Opacity
p {
opacity: 0.33;
}


Background
div {
background: red;
background: no-repeat center/80% url("image.png");
background: url("test.jpg") repeat-y;
}

Exercise
Let's write some styles π»

Box model

Box sizing
div {
box-sizing: border-box;
}

Positions

div {
position: relative;
}

z-index
div {
z-index: 2
}


Display
div {
display: block;
/* default */
}
div {
display: inline-block;
}
div {
display: inline;
}


Margins


Paddings


Border



CSS measurements


CSS measurements


CSS measurements
div {
/* property: calc(expression) */
width: calc(100% - 80px);
}

:before & :after

a::after {
content: "β";
}
a::before {
content: "β₯";
}


CSS Filters
img {
-webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */
filter: grayscale(100%);
}
filter: none | blur() | brightness() | contrast() | drop-shadow() | grayscale() | hue-rotate() | invert() | opacity() | saturate() | sepia() | url();




CSS Drawing

Exercise
Let's write some styles π»

Modern Layouting
CSS
Flexbox & CSS Grid π

Basis of layout
Float

img {
float: right;
margin: 0 0 1em 1em;
}

Basis of layout
Float layout
nav {
float: left;
width: 200px;
}
section {
margin-left: 200px;
}
nav.clearfix
section

Basis of layout
Inline-block layout
.nav
section
section
.nav {
display: inline-block;
vertical-align: top;
width: 25%;
}
.column {
display: inline-block;
vertical-align: top;
width: 75%;
}
.column

Centering content
Using padding
div {
padding: 20px;
display: inline-block;
}
Vertical centring - fixed size
div {
width: 100px;
height:100px;
}
.center {
display: table-cell;
vertical-align: middle;
text-align: center;
}



Responsive Web Design
Definition
βResponsive web design means designing your website so that it responds to your users environment based on screen size, platform and orientation.

Responsive vs. Adaptive


Breakpoints


RWD Components
-
Flexible, grid-based layouts
- % widths and em units, not fixed pixels
-
Flexible images and media
- width/height not fixed
-
CSS3 Media Queries
- @media rule

Flexible layout

.container {
width: 100vw;
}
.section {
width: 75%;
}
.aside {
width: 25%;
}

Flexible layout
Relative Viewport Lengths
- vw - Viewports width
- vh - Viewports height
- vmin - Minimum of the viewportβs height and width
- vmax - Maximum of the viewportβs height and width

Grid systems


Responsive images
<img srcset="image-320w.jpg 320w,
image-480w.jpg 480w,
image-800w.jpg 800w"
sizes="(max-width: 320px) 280px,
(max-width: 480px) 440px,
800px"
src="image-800w.jpg" alt="Some image">

Media queries
.container {
background: blue;
}
@media screen and ( min-width: 500px ) and ( max-width: 800px ) {
.container {
background: red;
}
}
@media screen and ( max-width: 500px ) {
.container {
background: green;
}
}

Viewport meta tag

<meta name="viewport" content="width=device-width, initial-scale=1">

Flexbox
CSS Flexible Box Layout, commonly known as Flexbox, is a CSS 3 web layout model.
The flex layout allows responsive elements within a container to be automatically arranged depending upon screen size.

Flexbox
<div class="container">
<div class="item">Red</div>
<div class="item">Orange</div>
<div class="item">Yellow</div>
<div class="item">Green</div>
<div class="item">Blue</div>
</div>


Flexbox
<div class="container">
<div class="item">Red</div>
<div class="item">Orange</div>
<div class="item">Yellow</div>
<div class="item">Green</div>
<div class="item">Blue</div>
</div>

.container {
display: flex;
}

Flexbox Axis


Flexbox Direction
<div class="container">
<div class="item">Red</div>
<div class="item">Orange</div>
<div class="item">Yellow</div>
<div class="item">Green</div>
<div class="item">Blue</div>
</div>
.container {
display: flex;
flex-direction: column; // row is the default
}


Flexbox Direction
<div class="container">
<div class="item">Red</div>
<div class="item">Orange</div>
<div class="item">Yellow</div>
<div class="item">Green</div>
<div class="item">Blue</div>
</div>
.container {
display: flex;
flex-direction: row-reverse;
}


Flexbox Order
.item:nth-child(5) {
order: -1;
}
.item:nth-child(2) {
order: 1; /* default is 0 */
}


Flexbox Alignment
<div class="container">
<div class="item">Red</div>
<div class="item">Orange</div>
<div class="item">Yellow</div>
<div class="item">Green</div>
<div class="item">Blue</div>
</div>
.container {
display: flex;
justify-content: center;
}


Flexbox Alignment
<div class="container">
<div class="item">Red</div>
<div class="item">Orange</div>
<div class="item">Yellow</div>
<div class="item">Green</div>
<div class="item">Blue</div>
</div>
.container {
display: flex;
justify-content: space-between;
}


Flexbox Centering
.container {
display: flex;
justify-content: center;
align-items: center;
}


Flexbox Grow
.container {
display: flex;
}
.item:nth-child(4) {
flex-grow: 1;
}


Flexbox Container


Exercise
Let's write some Flexbox π»

CSS Grid
built by those who did

1996 - βframe-basedβ layout model
2005 - Advanced Layout Module
Jan 2017 - Chromium 56 for Android
March 2017 - Firefox Mozilla
2 days later - Chrome
end of March - Opera + Safari

CSS Grid
Ironically, the last company to ship CSS Grid was Microsoft
A terrific example of standards success and cross-browser collaboration.
It closes the loop on a process that has been more than 20 years in the making.

Why CSS Grid
CSS Grid can do things Flexbox can't do
Flexbox - layout in a single dimension β in a row OR a column
CSS Grid - layout of items in two dimensions β rows AND columns
Explicit about the size of a grid item + the size your content takes up
It is the most powerful layout tool that we have invented for CSS. Yet

Grid Container

.container {
display: grid;
grid-template-columns: 40px 50px auto 50px 40px;
grid-template-rows: 25% 100px auto;
}

Grid Container
.container {
display: grid;
grid-template-columns: repeat(3, 20px) 5%;
}
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
.container {
display: grid;
grid-template-columns: 1fr 50px 1fr 1fr;
}

Grid Template Areas
.container {
grid-template-columns: 50px 50px 50px 50px;
grid-template-rows: auto;
grid-template-areas:
"header header header header"
"main main . sidebar"
"footer footer footer footer";
}
.item-a {
grid-area: header;
}
.item-b {
grid-area: main;
}
.item-c {
grid-area: sidebar;
}
.item-d {
grid-area: footer;
}


Grid Gap
.container {
display: grid;
grid-column-gap: 10px;
grid-row-gap: 15px;
}


Grid Alignment
.container {
justify-content: start;
}

.container {
justify-content: end;
}

.container {
justify-content: center;
}

.container {
justify-content: stretch;
}


Grid Alignment
.container {
justify-content: space-around;
}

.container {
justify-content: space-between;
}

.container {
justify-content: space-evenly;
}


Grid Items
.item-a {
grid-column-start: 2;
grid-column-end: five;
grid-row-start: row1-start;
grid-row-end: 3
}


Grid Items
.item-b {
grid-column-start: 1;
grid-column-end: span col4-start;
grid-row-start: 2;
grid-row-end: span 2;
}


Grid Items
.item-a {
align-self: start;
}
.item-a {
align-self: end;
}



Grid Items
.item-a {
align-self: center;
}
.item-a {
align-self: stretch;
}



Dev Tools


Exercise
Let's write some CSS Grid π»
Challenge 10

My first website
Intro to Web
Finally π¨π»βπ»

Files structure
βββ index.html
βββ style.css
βββ scripts.js
βββ images
βββ image-1.png
βββ image-2.png
βββ image-3.png
βββ index.html
βββ pages
βββ about.html
βββ services.html
βββ contact.html
βββ index.html
βββ styles
βββ style.css
βββ lib.css
βββ scripts
βββ myscripts.js
βββ lib.js
βββ images
βββ image-1.png
βββ image-2.png
βββ image-3.png

Exercise
Let's build the website π»
Challenge 11

Bootstrap (v5.1.3)
Build fast, responsive sites with Bootstrap


Exercise
Let's add Bootstrap π»
Challenge 12

A11y
Intro to Web
Because it matters π

What is Accessibility
The power of the Web is in its universality.
Access by everyone regardless of disability is an essential aspect.
Tim Berners-Lee, W3C Director and inventor of the WWW
Disabilities
- auditory
- cognitive
- neurological
- physical
- speech
- visual

A11Y
Without disabilities
- mobile, watches, smart TVs, small screens, different input modes, etc.
- older people
- βtemporary disabilitiesβ
- βsituational limitationsβ
- slow Internet connection, limited or expensive bandwidth

WCAG 2.1
Success criteria levels:
A (lowest)
AA (middle)
AAA (highest)

Color Contrast



Color Contrast

Patterns & signs


- common fonts - dyslexia
- at least 14px (0.875rem)
- relative values (%, rem, or em)
- only underline links
- markup instead of text on images
- 80 characters per line
- indentations and spacings

Typography
- @media prefers-reduced-motion
- allow control of sliders and carousels
- HTML Videos instead of animated GIFs
- prevent auto-play
- no parallax

Animations
.animation {
-webkit-animation: vibrate 0.3s linear infinite both;
animation: vibrate 0.3s linear infinite both;
}
@media (prefers-reduced-motion: reduce) {
.animation {
animation: none;
-webkit-animation: none;
}
}

Semantic



Headings


Images
<img src="blossoms.png" alt="Cherry trees in bloom on the UW campus">
Standard images
- CSS background-image
- empty alt=""
- role="presentation"
Decorative images

Keyboard & Focus
- tabindex in natural order
- Tab, Enter/ESC, Spacebar support
- links and buttons :focus, outline and title
- trap focus inside modal
* {
outline: none;
}
:focus {
outline: none;
}

Touch area
Target Size (Level AAA) - 44x44 px


A Better Web
Performance
Security
Accessibility
All websites created after 23 September 2018 will have to be accessible by 23 September 2019.
Existing websites will have to comply by 23 September 2020.
All mobile applications will have to be accessible by 23 June 2021.

EU

CSS Animations
CSS
Make the Web go round and round

Animations
/* The animation code */
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
/* The element to apply the animation to */
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}
Keyframes
"from" and "to" (which represents 0% (start) and 100% (complete)
/* The animation code */
@keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}
/* The element to apply the animation to */
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
}

Animations

Animations
- ease - Specifies an animation with a slow start, then fast, then end slowly (this is default)
- linear - Specifies an animation with the same speed from start to end
- ease-in - Specifies an animation with a slow start
- ease-out - Specifies an animation with a slow end
- ease-in-out - Specifies an animation with a slow start and end
- cubic-bezier(n,n,n,n) - Lets you define your own values in a cubic-bezier function
animation-timing-function
#div1 {animation-timing-function: linear;}
#div2 {animation-timing-function: ease;}
#div3 {animation-timing-function: ease-in;}
#div4 {animation-timing-function: ease-out;}
#div5 {animation-timing-function: ease-in-out;}

Animations
div {
animation-name: example;
animation-duration: 5s;
animation-timing-function: linear;
animation-delay: 2s;
animation-iteration-count: infinite;
animation-direction: alternate;
}

Animations
Shorthand property
div {
animation: example 5s linear 2s infinite alternate;
}


Animations

Complex animations

Intro to JS
JavaScript
Syntax, data types, console, debugging
- JavaScript was invented by Brendan Eich in 1995.
- It was developed in 10 days.
- It was developed for Netscape 2, and became the ECMA-262 standard in 1997.
- After Netscape handed JavaScript over to ECMA, the Mozilla foundation continued to develop JavaScript for the Firefox browser.
- Internet Explorer (IE4) was the first browser to support ECMA-262 Edition 1 (ES1).
- ECMA = European Computer Manufacturers Association
- ES2015 (ES6) is the latest version of JavaScript programming language. It is the first major upgrade to JavaScript since 1997

History
- Variables, objects,
- Data types
- Functions & Events
- DOM accessing
- Control Flow
- onClick, onload
- Hands on!

JavaScript Fundamentals


Implementation
<script type="text/javascript" src="script.js"></script>
1. External - as link
<script>
document.getElementById('demo').innerHTML = 'This is so awesome';
</script>
2. Internal - inside HTML

Handling
-
Handling browsers that donβt support JavaScript
<noscript>
Your browser does not support JavaScript so page
functionality will be significantly reduced.
</noscript>
-
Controlling loading style of script files:
- async - script is executed asynchronously while the page continues the parsing.
- defer - script is executed after the page has finished parsing.

Handling
Myth:
JavaScript is a scripting, interpreted language
Reality:
JavaScript engine compiles and immediately runs the code

Usage
document.getElementById ("idulMeu")
//accesses an HTML element with a unique unique id
innerHTML
//a property that defines the HTML content of an item
window.alert ("Alert: Pay attention!")
alert on the screen
//document.write ()
web page prints
//console.log (myVariable + "message")
console printing, debugging

Statements
x = y + 10;
literal
value
addition
operator
variable
(identifier)
assignment
operator
expression

Statements
1. var a = 2;
2. var b = 3;
3. a = b * 2;
4. b = b / 4;
5. var c = a + b;
- List of statements - executed in order
1. {
2. var a = 1;
3. var b = 2;
4. a = a + b;
5. }
- Grouping statements using { } - blocks

Primitives
1. Numbers
-
4, 24, 1034032, 4.56 etc.
- up to 2^53
- Special types of numbers: NaN, -Infinity, Infinity
2. Strings
- A collection of characters used to represent text
- Enclosed by single (') or double (") quotes
"This is some string"
'This is another string'
"And they're both great!"
"And then she said: \" Whoaaa! \"."

Primitives
3. Booleans
- A True/False value using the true and false keywords
- Falsey values
var myTrueVar = true;
var aFalseVar = false;
false
0 (zero)
'' or "" (empty string)
null
undefined
NaN

Operators
1. Addition ( + )
3 + 2 // => 5
'I am ' + 'the one!' // => 'I am the one'
1 + '2' // => 12
"I'm number " + 1 // => "I'm number 1"

Operators


Operators
2. Multiplication (*), Substraction (-) and Division ( / )
3 * 2 // => 6
4 / 2 // => 2
8 - 5 // => 3
'3' * 2 // => 6 , same for 3 * '2'
'a' * 2 // => NaN - conversion failed
'a' - 'a' // => NaN

Operators
3. Equality (==, === and !=, !==)
1 == 1 // => true
'abc' === 'abc' // => true
1 == '1' // true
1 === '1' // false
1 !== '1' // true
1 < 2 // true
2 >= 3 // false

Operators
4. Logical operators: and (&&), or (||), and not (!).
'Apples' == 'Oranges' && 5 > 3 //
5 > 10 || 4 < 2 //
3 < 10 && 10 > 8 //
7 > 5 || 1 > 2 //
!(7 > 5 || 1 > 2) //

Variables
var myVariable; // value is undefined
- Declaring a variable
var myVariable;
myVariable = 42;
- Assigning a value to a variable
var myVariable = 42;
var myOtherVariable = myVariable / 2;
- Using a variable
var myNumber = 42;
myNumber = 'forty two';
- Variables are dynamic

Variables
Variable names:
- Can contain numbers, but they cannot begin with a number
-
Must not contain mathematical or logical operators.
-
Must not contain any punctuation marks of any kind other than the underscore (_) and dollar sign ($).
-
Must not contain any spaces
-
Must not be JavaScript keywords, but they can contain keywords
-
Are case-sensitive

Exercise
- The DOM (Document Object Model) represents a hierarchy of objects, forming a model of your HTML document.


DOM

DOM

- Window - represents the browser window object
- Navigator - object linking to browser specific APIs
- Document - an object representing the page loaded in the window. Use this to get references to elements and manipulate any HTML or CSS related properties

Accessing DOM Elements
<div id="main">
<div class="pictureContainer">
<img class="theimage" src="smiley.png" height="300" width="150"/>
</div>
<div class="pictureContainer">
<img class="theimage" src="tongue.png" height="300" width="150"/>
</div>
<div class="pictureContainer">
<img class="theimage" src="meh.png" height="300" width="150"/>
</div>
<div class="pictureContainer">
<img class="theimage" src="sad.png" height="300" width="150"/>
</div>
</div>
- Getting elements by their id
var container = document.getElementById('main');
// get element with #main
container; // div#main object
container.style
container.addEventListener(...)
container.appendChild(...)

Accessing DOM Elements
<div id="main">
<div class="pictureContainer">
<img class="theimage" src="smiley.png" height="300" width="150"/>
</div>
<div class="pictureContainer">
<img class="theimage" src="tongue.png" height="300" width="150"/>
</div>
<div class="pictureContainer">
<img class="theimage" src="meh.png" height="300" width="150"/>
</div>
<div class="pictureContainer">
<img class="theimage" src="sad.png" height="300" width="150"/>
</div>
</div>
- Getting elements by class name
// get elements with .theimage
var images = document.getElementsByClassName('theimage');
Array.from(images).forEach(pict => {
console.log(pict.tagName); // IMG, IMG, IMG, IMG
})

Accessing DOM Elements
<div id="main">
<div class="pictureContainer">
<img class="theimage" src="smiley.png" height="300" width="150"/>
</div>
<div class="pictureContainer">
<img class="theimage" src="tongue.png" height="300" width="150"/>
</div>
<div class="pictureContainer">
<img class="theimage" src="meh.png" height="300" width="150"/>
</div>
<div class="pictureContainer">
<img class="theimage" src="sad.png" height="300" width="150"/>
</div>
</div>
- Getting elements by CSS selectors
var images = document.querySelectorAll('theimage');
images;
// NodeList(4) [img.theimage, img.theimage, img.theimage, img.theimage]
var picture = document.querySelector('.pictureContainer');
var container = document.querySelector('#main');
var notAnElement = document.querySelector('not-a-tag');
picture; // HTMLPictureElement
container; // HTMLDivElement
notAnElement; // null

Modifying DOM Elements
<div class="my-element">
This is the content of <span> my </span> element
</div>
- Changing the content of an element
var elem = document.querySelector('.my-element');
elem.innerHTML = 'Some other content of <span> mine </span>';

Modifying DOM Elements
<p>One</p>
<p>Two</p>
<p>Three</p>
- Adding a new node
var newElement = document.createElement('p'); // create a new <p> element
newElement.textContent = 'Four'; // change the text content
document.body.appendChild(newElement); // attach it to the DOM
// <p> One </p>
// <p> Two </p>
// <p> Three </p>
// <p> Four </p>
var paragraphs = document.body.getElementsByTagName("p");
// all <p> elements
document.body.insertBefore(paragraphs[2], paragraphs[0]);
// add third after first
// <p> Three </p> <-- dom element can only appear once in document
// <p> One </p>
// <p> Two </p>
// <p> Four </p>

Modifying DOM Elements
- Changing/adding attributes
var button = document.querySelector('button');
button.disabled = false;
var paragraph = document.querySelector('p');
paragraph.getAttribute('data-secret'); // don't tell anyone
<p data-secret="don't tell anyone">Title</p>
<button disabled="true">CLICK ME!</button>

Modifying DOM Elements
- Modifying styles
var paragraph = document.querySelector('p');
paragraph.style.color = 'red'; // set new color to red
paragraph.style.height; // '' <- not explicitly set
window.getComputedStyle(paragraph).height; // '18px'
paragraph.style.height = '50px';
console.log(paragraph.style.height); // '50px'
window.innerWidth; // browser current width
window.innerHeight; // browser current height
<p style="color: purple">
Some text
</p>

Exercise
{
statement_1;
statement_2;
.
.
.
statement_n;
}
Block statements are used to group statements together

Blocks

If/else conditional
if (condition) {
// code block if contition evaluates to true
}
if (condition) {
// contition is true
} else {
// condition is false
}
if (condition1) {
// contition1 is true
} else if(condition2) {
// contition2 is true
} else { // condition1 AND condition2 is false }

While/do loop
while (condition) {
// code gets executed as long as
// condition evaluates to true
}
- do...while - code gets executed at least once
do {
// code runs once
// and then gets executed as long as
// condition evaluates to true
} while (condition)

Breaking out of loops
var a = 0;
while (true) {
if( a >= 5 ) {
break;
}
a = a+1;
}

For loop
for ([initialExpression]; [condition]; [incrementExpression]) {
// code gets executed as long as
// condition evaluates to true
}
for (var variable=startvalue; variable < endvalue; variable = variable + increment) {
// code to be executed
}
for (var i=0; i<5; i++) {
console.log(i);
}
// 0 1 2 3 4
Using the for loop for iterations

Try/catch
try {
var a = 2 / b; // b is not defined
}
catch(e) {
alert('The following error occurred: ' + e.message)
}
finally {
alert('Finally block executed')
}
- Catching code errors
throw 'Error2'; // String type
throw 42; // Number type
throw new Error('something happened') // Error object
- Throwing custom errors

Exercise
Let's write some JS π»
Challenge 4 + 5

Functions
- Declaring a function
function add(a, b) {
return a + b;
}
declaration
keyword
function name
function parameters
function return value
- Using (invoking) a function
var a = 1;
var b = 2;
var myVar = add(a, b);
arguments
assignment to function return value

Function scope
var addition = 10; // defined in global scope
function processNumber(num) {
var multiply = 2; // function scoped variable
// available only in function
// block - {}
// OK: use external scoped variable 'addition'
return (num * multiply) + addition;
}
var res = processNumber(5); // 20
console.log(multiply);
// ReferenceError: num is not defined

Closure
function init() {
var name = 'Mozilla';
// name is a local variable created by init
function displayName() {
// displayName() is the inner function, a closure
alert(name);
// use variable declared in the parent function
}
displayName();
}
init();

Callbacks
function callback() {
console.log('callback')
}
function caller(cb) {
cb();
}
caller(callback); // 'callback'
Functions can be passed as arguments to other functions

Events
- Simple event listeners
var inputedText = ''
document.querySelector('input').addEventListener('input', function(event) {
inputedText = event.target.value; // display the last modified value of the input
})
function handler() { // handler function
console.log(inputedText); // get the curent text in the input
}
var button = document.querySelector('button')
button.addEventListener('click', handler); // register handler
button.removeEventListener('click', handler); // remove handler
<button>Click me!</button>
<input placeholder="Write here...">

Events
- The event object
var button = document.querySelector("button");
button.addEventListener("mousedown", function(event) {
if (event.button == 0) {
console.log("Left button");
} else if (event.button == 1) {
console.log("Middle button");
} else if (event.button == 2) {
console.log("Right button");
}
});
<button>Click me!</button>
<input placeholder="Write here...">

Events
- The event object
var input = document.querySelector("input");
input.addEventListener("keydown", function(event) {
if (event.key == "r") {
button.style.background = "red";
}
});
input.addEventListener("keyup", event => {
if (event.key == "v") {
button.style.background = "";
}
});
<button>Click me!</button>
<input placeholder="Write here...">

Events
- Event propagation
<div>
<button>Click me!</button>
</div>

var div = document.querySelector('div');
var button = document.querySelector('button');
// button handler
button.addEventListener('click', function(event) {
console.log('button click');
event.stopPropagation(); // event stops here
});
// div handler
div.addEventListener('click', function(event) {
console.log('div click');
});

Events
- Preventing default behaviour
<a href="https://developer.mozilla.org/">MDN</a>
var link = document.querySelector("a");
link.addEventListener("click", function(event) {
console.log("Won't navigate away");
event.preventDefault();
});

Events
- Document ready
document.addEventListener("DOMContentLoaded", function() {
// the browser fully loaded HTML, and the DOM tree
// is built, but external resources like pictures <img>
// and stylesheets may be not yet loaded.
});
window.onload = function() {
// the browser loaded all resources (images, styles etc).
};

Events
- Timers
var timer = setTimeout(function() {
console.log("It's time"); // will call after aprox 500ms
}, 500);
let ticks = 0;
let clock = setInterval(function() {
console.log("tick", ticks++);
if (ticks == 10) {
clearInterval(clock); // stops the timer
console.log("stop.");
}
}, 200); // will call every aprox 200ms

Events
- Client-side handling of forms
<form id="theForm" >
<input id="name" name="name">
<input type="submit">
</form>
let form = document.querySelector('#theForm')
form.addEventListener("submit", function (event) {
event.preventDefault();
const nameInput = document.getElementById('name');
let nameValue = nameInput.value;
console.log(nameInput.validity.valid); // true/false
// do something depending on form state
});

Exercise
Let's write some JS π»
- Object
- Array
- Boolean
- Symbol
- Error
- Number
- String
- RegExp
- Math
- Set

Objects


Arrays
- A collection object that has a sequence of items you can access and modify
var skills = [ 'HTML', 'CSS', 'JS' ];
var fibonacci = [ 1, 1, 2, 3, 5, 8, 13 ];
var array = [ 'string', 42, {name: 'Andrei'}, [1, 2, 3] ];
- Access items using bracket nottaion and index for item position in collection
fibonacci[4] // 5 - array is 0 indexed
skills[1] = 'Python' // directly change a value
array[3][1]; // 2 - multidimensional array

Arrays
- Obtaining the length of the array
var skills = [ 'HTML', 'CSS', 'JS' ];
skills.length; // 3
skills[3] = 'Python';
skills; // [ 'HTML', 'CSS', 'JS', 'Python' ];
skills.length; // 4
skills [9] = 'C++';
skills; // [ 'HTML', 'CSS', 'JS', 'Python', , , , , , 'C++' ]βββββ
skills.length; // 10
skills[6]; // undefined

Arrays
- Iterating arrays
var fibbonacci = [1, 1, 2, 3, 5, 8, 13, 21];
//for loop
for (var i = 0; i < fibbonacci.length; i++) {
console.log(fibbonacci[i]); // 1, 1, 2, 3, 5, 8, 13, 21
}
// for...in loop
for (var index in fibbonacci) {
console.log(fibbonacci[index]) // 1, 1, 2, 3, 5, 8, 13, 21
}
// for...of loop
for (var number of fibbonacci) {
console.log(number) // 1, 1, 2, 3, 5, 8, 13, 21
}

Arrays - forEach()
- executes a provided function once for each array element, without changing the array.
var skills = ['HTML', 'CSS', 'JS'];
skills.forEach(function(skill) {
console.log(skill);
});
// HTML
// CSS
// JS
skills.forEach(function(skill, index) {
console.log(
'Skill ' + (index + 1) + ': ' + skill.toLowerCase()
);
});
// βββββSkill 1: htmlβββββ
// βββββSkill 2: cssβββββ
// βββββSkill 3: jsβββββ

Array Methods
- Concatenating 2 arrays
var skills1 = [ 'HTML', 'CSS', 'JS' ];
var skills2 = ['Python', 'Java'];
var skills = skills1.concat(skills2);
// [ 'HTML', 'CSS', 'JS', 'Python', 'Java' ]βββββ
- Finding items
var skills = [ 'HTML', 'CSS', 'JS' ];
skills.indexOf('JS') // 2
skills.indexOf('Python') // -1
skills.includes('HTML') // true
skills.includes(123) // false

Array Methods
- Modifying an array
var skills = [ 'HTML', 'CSS', 'JS' ];
// add at the end
skills.push('Python'); // βββββ[ 'HTML', 'CSS', 'JS', 'Python' ]βββββ
// remove from end
skills.pop(); // [ 'HTML', 'CSS', 'JS' ]
// remove from start
skills.shift(); // [ 'CSS', 'JS' ]βββββ
// add to start
skills.unshift('Java'); // βββββ[ 'Java', 'CSS', 'JS' ]βββββ

Array Methods
- Working with strings
var names = 'Andrei George Elena Maria';
names.split(' ') // βββββ[ 'Andrei', 'George', 'Elena', 'Maria' ]βββββ
var skills = ['HTML', 'CSS', 'JS'];
skills.join(', ') // 'βββββHTML, CSS, JSβββββ'
- Working with strings
var name = 'Diana Miron';
name.charAt(2) // a
name[2] // a

Array Methods
var names = 'Andrei George Elena Maria';
names.sort();
names.slice();
names.splice();
names.find();
names.includes();
names.filter();
names.map();
names.reduce();

Objects
var basicObject = {};
A collection of key/value pair data (similar to a dictionary)
Can contain primitives, functions, arrays and/or other objects:
const anObject = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
// ...
}
keys
values
properties

Objects
- Literal notation
var person = {
sex: 'female', // string
age: 29, // number
name: { // nested object
'first': 'Diana',
'last': 'Miron'
},
skills: ['HTML', 'CSS', 'JavaScript'], // array
sayHello: function() { // method
console.log('Hello, friends!')
},
favoriteFood: null // null value
};

Objects
person.age; // 29
person.age = 32; // change the value
person.skills[0]; // 'HTML'
person.sayHello(); // call the function -> 'Hello, friends!'
person.name.first; // 'Diana'
person.isStudent = false; // add a new property to the object
delete person.isStudent; // remove property from the object
- Dot notation
person.name
object
property name
dot operator

Objects
var person = {
name: {
first: 'Diana',
last: 'Miron'
},
education: {
schoolName: 'ASE',
yearGraduated: 2013
}
};
person.name.first; // 'Diana'
person.education.yearGraduated; // 2013
- Nested objects

Objects
person['age']; // 29
person[age] // ReferenceError: age is not defined
person['age'] = 18; // change the value
person['name'].first; // 'Diana'
person['isStudent'] = false; // add a new prop to the object
- Bracket notation
person['name']
object
property name

Objects
- Testing if objects have properties
var person = { name: 'Diana' };
if ('name' in person || person.name !== undefined) {
// is true
}
if ('age' in person || person.age) {
// is false
}
- Getting all the object keys
var person = {
name: 'Diana',
age: 29,
sex: 'female'
};
var keys = Object.keys(person) // [ 'name', 'age', 'sex' ]βββββ
for(var key in person) {
console.log(person[key]);
}
- Iterating object keys

this
- this is used in functions refer to the object the function is being called from
var person1 = {
age: 29,
printAge: function() {
console.log( 'My age is ' + this.age );
}
};
person1.printAge(); // 29 - this will refer to person1
var person2 = { age: 25 };
person2.printAge = person1.printAge;
person2.printAge(); // 25 - this will refer to person2

Classes(ES6)
class Person {
constructor(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
printName() {
console.log('Hello, my name is ' + this.name);
}
}
var p = new Person('Andrei', 31, 'male');
p.age; // 31
p.printName(); // 'Hello, my name is Andreiβββββ'
p.age = 'thirty one'; // asign new value of new type

JSON
{
"name": "Diana Miron",
"age": 29,
"skills": [
{ "name": "HTML", "level": 7 },
{ "name": "CSS", "level": 8 }
]
}
- A language agnostic data exchange format
- Contains only data (primitives, arrays, other objects), no methods
var person = JSON.parse(paersonJSON); // decode JSON
var json = JSON.stringify(paerson); // encode JSON

Build-in objects
- Date
Math.PI; // 3.141592653589793
Math.round(4.7); // 5
Math.ceil(4.4); // 5
Math.floor(4.4); // 4
Math.random(); // [0,1)
- Math
var myDate = new Date(1995, 11, 17);
myDate.getFullYear(); // 1995
myDate.getMonth(); // 10 - months represented 0-11
myDate.getTime(); // 819151200000 - milliseconds since January 1, 1970

Exercise
Let's write some JS π»
Challenge 7 + 8

HTTP requests


HTTP requests


HTTP requests

- REST API

XMLHttpRequest
//create XMLHttpRequest object
const xhr = new XMLHttpRequest()
//open a get request with the remote server URL
xhr.open("GET", "https://world.openfoodfacts.org/category/pastas/1.json")
//send the Http request
xhr.send()
//EVENT HANDLERS
//triggered when the response is completed
xhr.onload = function() {
if (xhr.status === 200) {
//parse JSON datax`x
data = JSON.parse(xhr.responseText)
console.log(data.count)
console.log(data.products)
} else if (xhr.status === 404) {
console.log("No records found")
}
}
//triggered when a network-level error occurs with the request
xhr.onerror = function() {
console.log("Network error occurred")
}
- GET

XMLHttpRequest
// create XMLHttpRequest object
const xhr = new XMLHttpRequest()
// open a POST request
xhr.open("POST", "/food")
// set content-type header to JSON
xhr.setRequestHeader("Content-Type", "application/json");
// send JSON data to the remote server
xhr.send(JSON.stringify(food))
// Event Handlers
//
// triggered when the response is fully received
xhr.onload = function(response) {
console.log(response)
}
- POST

Exercise
Let's write some JS π»
Challenge 9 + 10 (optional)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Example</title>
<script type="text/javascript" src="Scripts/jquery-3.3.1.min.js">
</script>
</head>
<body>
...
<script type="text/javascript">
$(document).ready(function () {
// some code
});
</script>
</body>
</html>

jQuery

jQuery
- Selecting elements and traversing the DOMβ
$(document).ready(function () {
$("h2").each(function () {
this.style.color = "red"; // this -> currently selected element
});
});
- Tag name - $("h2")
- Element ID - $("#logo")
- Element class - $(".blue")
- An attribute on an element - $("input[type=text]")

jQuery
- Selecting elements and traversing the DOMβ
$( "span.subchild" ).parent();
- Parents
- Children
β
- Siblings
$( "div.grandparent" ).children( "div" ); // direct children only
$( "div.grandparent" ).find( "div" ); // all descendants
$( "div.parent" ).siblings();
$( "div.parent" ).next();
$( "div.parent" ).prev();

jQuery
- Adding, Removing, and Modifying Elements
- append( htmlString )
β
- html( htmlString )
- detach()
$("#list").append("<li>The new last list item</li>");
$("#Warning").detach();
$(".title").html("<h1>New Heading</h1>");

jQuery
- Adding, Removing, and Modifying Elements
$("#Warning").replaceWith("<p>Panic Over!</p>");
- replaceWith( htmlString)
- val()
β
- attr()
$("input[type=text]").val();
$("button").attr(disabled,"disabled");

jQuery
- Styling elements
// GET
$("p").css("font-size");
$("p").css("fontSize");
// SET
$("p").css("fontSize", "10px");
$("p").css({
fontSize: "10px",
color: "red"
})
h1.addClass( "big" );
h1.removeClass( "big" );
h1.toggleClass( "big" );
if ( h1.hasClass( "big" ) ) {
...
}
- Handling events
$(document).ready(function () {
$("#submit").bind(βclickβ, function () {
var userName = $("#NameBox").val();
$("#thankYouArea").replaceWith("<p>Thank you " + userName + "</p>");
})
});
- Use the jQuery selector function to find the item that initiates the event
- Use the bind method (or a shortcut) to bind the event handler to the eventβ

jQuery
- Handling events
- click(), dblclick() : Binds to mouse click events.
- error() : Binds to occurrence of errors in the document such as broken links and missing images.
- focus(), focusin(), focusout() : Binds to element focus events.
- keydown(), keyup(), keypress() : Binds to user keyboard input events.
- hover(), mousedown(), mouseup(), mouseenter(), mouseleave(), mouseout(), mouseover(), mousemove() : Binds to mouse and cursor-related events.
- load(), unload() : Binds to events triggered when a specified element is loaded or unloaded on the page.

jQuery
- AJAX (Async JavaScript And XML)
// Using the core $.ajax() method
$.ajax({
url: "post.php", // The URL for the request
type: "GET", // Whether this is a POST or GET request
dataType : "json", // The type of data we expect back
success: function(data) { console.log(data) }
})
// POST: add data: {}

AJAX

Local & Session Storage
// set item
localStorage.setItem("name", "diana");
//get item
localStorage.getItem("name");
//delete any key
localStorage.deleteItem("name");
//clear all keys
localStorage.clear();
local storage
session storage
// set item
sessionStorage.setItem("name", "diana");
//get item
sessionStorage.getItem("name");
//delete any key
sessionStorage.deleteItem("name");
//clear all keys
sessionStorage.clear();

Exercise
Let's write some JS π»
Challenge 11

Q&A
Any questions & curiosities?
Personal Feedback
Thank you!

JSLeague Intro to Web - Dec 2021
By Diana Gabriela Miron
JSLeague Intro to Web - Dec 2021
- 661