HTML, CSS, JS

Link to the course and TDs

This lesson plus the TD can be found at: https://github.com/benjaminvella/HarmoWeb

If you know how to use Git, clone the repo.

If you don't, click "Code" --> "Download ZIP".


Also, keep in mind that this lesson has been written in HTML, CSS, and JS, so if you need examples about something explained in the slides, simply open this file in an editor and read it, I used most of what is taught in this course to build the slides (and the code is commented).

Content

HTML

Introduction

HTML (HyperText Markup Language) is a markup language used to define the content of a page.

1989 : Tim Berners-Lee writes a paper about a way to share information efficiently.

1990 : Development of the 3 main web technologies: URL to locate a document, HTTP protocol to communicate, and HTML to display information --> The World Wide Web (www) is born.

1991 : First public web page ever created

2014: HTML5 is released to the world.

HTML

HTML5

HTML has evolved throughout the years to match the needs of the society, from a way to share data with a few people to the main information hub and selling/buying platform for billions of people around the world.

The last major revision of HTML - HTML5 - focus on semantics: it adds tags which have a meaning, so that machines (and humans) can easily understand what the content represents.

HTML

Markup syntax

HTML uses tags to encapsulate data: <tagName propertyName1="propertyValue1" propertyName2="propertyValue2" ... > Content </tagName>

Some tags cannot contain any content, in which case you must not add a closing tag. It's the case of img, meta, link and a few others: <img src="pathOrUrlToImage" alt="Alternative text in case the image cannot be displayed" >

Content of a tag can be data (text, image, ...) but also other tags, creating a tree: <section>
    <h1>Section title</h1>
    <article>
        <h2>Article title</h2>
        <p>Content of the article</p>
    </article>
</section>

HTML

HTML5 Structure

To create an HTML5 page, you need to declare a given doctype. After that you can start the page markup tree.

Everything should be encapsulated in a html tag having a lang attribute.

Inside the html tag, only 2 possible tags: <head> and <body>.

<head> contains all the non-visible content (metadata, description, CSS, ...).

<body> contains all visible elements (text, images, links, ...).

HTML

HTML5 Structure - head

<head> contains the non-visible elements: descriptions, configurations, scripts, style, links to external resources, ...

- <script> tag is usually associated with JavaScript, but its type attribute can be specified, allowing other scripts to be executed. To load an external JavaScript file, use this tag and add the src attribute to link to the file to load. async attribute makes the script download asynchronously, and defer attribute makes it also load after the page has been parsed.

- <link> tag is used to connect to another document. It requires 2 attributes: rel and href. href's value is the URL to the resource ; rel's value is the type of link to create: most often it will be "stylesheet" indicating the need to load a CSS file, but it can also be "preconnect" for instance, to ask the browser to prepare connections to the given URL.

HTML

HTML5 Structure - head

- <meta> tag represents metadata about the page, may it be description, encoding, or other configurations. Its attributes depend on which metadata will be represented, but it usually is name for the type of metadata and content for the value. (The most common exception is the charset, which is mandatory and written like in the example on the right.)

- <style> allows to write CSS rules directly inside the HTML document (it is the case in this page to reduce the number of files).

- <title> is the text written in the current tab of the browser.

HTML

HTML5 Structure - body

<body> contains the visible elements: text, images, video, graphs, tables, ...

The structure of a page is very important, and especially in HTML5. To easily understand the layout, some tags have been created: <body>
    <header>Top of the page, for logo, login, search bar... </header>
    <nav>Menu </nav>
    <main>Main content of the page </main>
    <aside>Side content related to the main </aside>
    <footer>Bottom of the page, for links, contact, sitemap, ... </footer>
</body>

HTML

HTML5 Structure - body

Having a clear layout is not enough: pages may be big, and it has become necessary to be able to extract parts of a page (may it be for sharing on social media, or having a robot extract data from them). That's why some tags exist to describe the content of the main part of a page: <section>
    <h1>Sections must have a title.</h1>
    <article>
        <h2>Articles too must have a title.</h2>
        <p>In this example an article is inside a section, but articles can also have sections. </p>
    </article>
</section>

Plenty of other tags exist. For instance, in this page <code> have been used to display lines of code, <small> to add small notes below a content, and <a> for links. An exhaustive list can be found here.
Sometimes, meaningless tags are required for layout or styling purposes. In this case, <div> and <span> are the default "block" and "inline" tags (see CSS parts for more info on that).

HTML

Common HTML tags

<!-- div and span are respectively the standard bloc and inline elements. They do not bear any meaning. --> <div> <span>Random text</span> </div>

<!-- A paragraph is represented by the p tag. --> <p>Lorem Ipsum Dolor Sit Amet...</p>

<!-- Links use the href attribute to define their target. It can be a URL, a phone number, a mail, as long as the href's value is correct, it will work. If you want the link to open in a new tab, you can add the attribute: target="_blank". --> <a href="tel:+33836656565" target="_blank">Click to call Santa in France (in the 90's at least)</a> Reference can be found here.
<!-- A button is represented by the button tag. --> <button>Click me !</button>

<!-- Titles are usually represented by a h[1-4] tag. --> <h1>Title</h1>
<h2>Sub-title</h2>
<h3>Sub-sub-title</h3>
<h4>Sub-sub-sub-title</h4>

HTML

Common HTML tags

<!-- image elements must have an alt attribute which will be displayed if the image doesn't load, and an src attribute containing the URL of the image (the URL can be relative to the current page). --> <img src="path/to/the/image.webp" alt="text describing the image">

<!-- For a video, you need the src attribute to link to the video, and you can add the "controls" attribute if you want play/stop and fullscreen buttons to be automatically added. Also, the content of the tag must be the text to display if the video doesn't load. --> <video controls src="path/to/the/video.mp4">Video is about blah blah blah</video>

<!-- An iFrame allows to load another HTML page / website inside your page. The only required property is src, linking to the HTML page to load, but there are many other properties that can be set to handle the iframe, you can find them here --> <iframe src="google.com"></iframe>

<!-- Canvas allows drawing, but the APIs are way too complex to be defined in this guide. If you want to know more, you can start by the documentation and/or find tutorials online. For now, know that canvas require a width and height, and that the content of the tag is a message in case the browser cannot display the canvas. All the drawing is actually done in JavaScript (... unless you want to draw in 3D, but that's another story). --> <canvas width="600px" height="800px">Sorry, your browser cannot display canvas.</canvas>

HMTL, CSS, JS

CSS part

CSS

CSS - Introduction

CSS (Cascading Style Sheets) is the language used to define the style of a page, from the global layout to the color of a letter.

It allows the developer to write rules which apply to a chosen set of HTML elements, and add some properties to them to change their style.

It is also possible to choose the conditions in which a CSS rule will apply (for instance, some properties applied only when the user's mouse hovers something).

CSS

CSS - Syntax

CSS can be written in a <style> tag in the <head> part of the page, or in an external CSS file.

In any case, the content of the <style> tag is the same as the content of a CSS file: for each rule, 1 or more selectors separated by commas, a pair of brackets, and inside the brackets a list properties to change and their values. For instance: /* Rule 1 */ body {
    color: red;
}
/* Rule 2 */ article, div {
    background-color: blue;
}
1) Colorizes all the texts of the <body> and its children in red.
2) Paints the background of all <article> and <div> elements in blue.

CSS

CSS - Selectors

To understand how to select an element, the first step is to understand what are the characteristics of an HTML element. Given the example on the right, the red line:

1) Is a <div>. In CSS we can select a tag by simply writing its name: div {color: blue;} Note that it would also select the green div.

2) Has an id, uniqueId42. IDs must be unique, so it's an easy way to be sure only 1 element will be selected. Targeting an ID in CSS is done by using #: #uniqueId42 {color: blue;}

CSS

CSS - Selectors

Given the example on the right, the red line:

3) Has 2 classes, foo and bar. In CSS we can select a class by using . (dot): .foo {color: blue;} Note that this would also select the article.

3bis) It is possible to select elements which have multiple particularities: div.foo {color: blue;} will select all <div> which have a class foo. The only one matching all those criteria is the red element (<article> is not a <div>, and the green <div> doesn't have the foo class). Note that .foo.bar {color: blue;} would have also worked to select only the red div since it's the only one having both classes.

CSS

CSS - Selectors

Given the example on the right, the red line:

4) Is a sibling (same tree level) of <h1>. In CSS we can select a sibling placed after a given element by using ~ (tilde): h1 ~ div {color: blue;} Note that this would also select the green div because it is also a sibling of h1 appearing after.

4bis) Is a DIRECT sibling of <h1> (an element placed at the same level, directly after h1). In CSS we can select a sibling placed right after a given element by using +: h1 + div {color: blue;}

CSS

CSS - Selectors

Given the example on the right, the red line:

5) Is a descendant of <article>. In CSS we can select a descendant by simply separating selectors by a space: article div {color: blue;} Note that this would also select the green div because it is also a descendant of article.

5bis) Is a child of <article>. In CSS we can select a child by using >: article > div {color: blue;} Note that this would also select the green div because it is also a child of article.

CSS

CSS - Selectors

We have seen almost all the most common ways to select the red element, but we are missing one important part: pseudo-classes.

A pseudo-class is a keyword or a function added to a selector to get more precise information about it. The list can be found here.

For instance, the pseudo class :nth-child(k) selects elements which are the kth children of their parents. In our example, the red div is the second child of its parent (first is h1, third is the green div), so we could use: div:nth-child(2) {color: blue;}

CSS

CSS - Selectors

We won't see all pseudo-classes, but let's cite 2 of them which drastically change the way to think CSS.

:has(selector) matches the parent of the given selector ! For instance, a:has(> img) will select all <a> elements having an img has child.

:is(selectors) allows to regroup parents to write shorter CSS. For instance, :is(header, main, footer) p will select all <p> elements which are descendants of either header, main, or footer elements. For comparison, wihtout :is() we would have written header p, main p, footer p

CSS

CSS - Priority

Let's say different rules target the same element. Then they are merged and all apply. But what if they set different values for the same property (for instance, color: blue; and color: red;) ?

CSS sorts the selectors by precision. Then, if it has to choose between values, it will take the value of the most precise selector. Order is: id >> class >> tag >> attribute.

If a selector is composed of multiple elements (#myId article p.blabla { }), it will "sum" the importance of each individual selector (imagine 0.1 point for each attribute, 1 point for each tag, 10 for each class, and 100 for each id in the selector. This is not a real calculation: setting 11 classes won't make the selector more important than 1 id. It's just the idea.

CSS

CSS - Priority

More exactly, CSS engines read CSS in the order it is given to it, and whenever it has to update a property's value for an element, it will do so unless the selector from which last value was set is more precise than the current one. That is why, if 2 selectors have the same precision, the last one read by the engine will have priority.

There is a way to overwrite this feature and force the CSS engine to keep the value from a lesser-precise selector: by adding "!important" after a key/value pair.

CSS

CSS - Dimensions

Let's consider the image below. In this image, we will focus on the dimensions of the RED rectangle. The blue one is its parent (the container) and the green one is the content (its child).

Layer 1

CSS

CSS - Dimensions

Let's consider the image below. In this image, we will focus on the dimensions of the RED rectangle. The blue one is its parent (the container) and the green one is the content (its child).

Layer 1

CSS

CSS - Dimensions

2 useful points to note about dimensions:

Margins, paddings, and border can be negative. This can be used to revert another attribute's property. For instance, you can use a negative margin to place an element closer to another than it would normally be.

In the picture on the previous slide, the blue arrow representing the width was incorrect. Width can either be the content and only the content (meaning that an element with a 200 pixels width, 10 pixels padding on both sides and 5 pixels borders on both side will actually require 230px to be displayed), or the entirety of the element (meaning the actual size of the content will be: width - borders - paddings). If that's not clear, here is a demo. Both can be useful depending on the context. To choose what you mean by width on a given element, use box-sizing (for instance, box-sizing: border-box;).

CSS

CSS - Units

When a size needs to be defined (may it be for width, margin, font size, or anything that require a size), many units are available in CSS.

px means pixels. It's not really the pixels of the screen, but the idea is that it is a fixed value.

% represents a percentage of the parent's same attribute. Be careful though, it works only if the parent has a defined size.

vw/vh: vw is viewport width, 1vw is 1% of the width of the browser ; vh is the same but for the height of the browser.

(r)em: em is the computed value of the font-size of the current element ; rem is the computed value of the font-size of the root element.

... and a few others, but they are way less used.

CSS

CSS - Display

display is a CSS property which define the characteristics of an element (what space does it naturally take, which properties can be used on him to modify its position and size, ...).

There are 5 possible values for display: inline, block, inline-block, flex, and grid. Actually, there are a few more, such as table, but they are so 2002 that we won't talk about them.

By default, all HTML elements are either inline or block. Except <table>...

CSS

CSS - Simple displays

Inline elements (such as <span> or any element on which the CSS code display: inline; is used) take only the space they need, both horizontally and vertically. You cannot resize them, or add a margin or padding on them (for instance, width: 300px; would do nothing).

Block elements (such as <p> or any element on which the CSS code display: block; is used) take only the space they need vertically, but use all the horizontal space of their parent. You can resize them and apply margin and padding (e.g., width: 300px; would force the width of the element to be 300px).

Inline-Block elements (any element on which the CSS code display: inline-block; is used) will take the best of both inline and block worlds: elements will only take the space they need horizontally and vertically, while allowing resize, margins and paddings !

CSS

CSS - Flexbox

display: flex; activates the flex display for the given elements and its children. To understand how it works, there are 2 great ressources on the web that I HIGHLY recommend:

Flexbox Froggy is a game where you have to put the correct CSS for the frogs to reach their water lilies. There are 24 levels, but each require less than a minute, and they go from the basics of flexbox to some advanced layouts, always in less than 5 lines of code.

Once you have successfully resolved all the Flexbox Froggy exercises, the second resource is the clearest cheatsheet I have ever seen about flexbox.

CSS

CSS - Grid

display: grid; is another magical tool of CSS, used to display items like if the container was a table.

Grid Garden is a game made by the same company as Flexbox Froggy and the concept is the same, but for grids.

Once you've mastered the CSS attributes to write to reach you dream layout, the next resource shows how to build 10 classic layouts in a few lines of code , using either flex or grid. I strongly advise you to take a look, at least to see what can be achieved easily with those features.

CSS

CSS - Positioning

position is a CSS property which define how the position of an element can be manipulated in CSS.

There are 5 main possible values for position: unset, fixed, absolute, relative, and sticky. Once the position attribute is set to a value, 4 new properties become active: top, right, left, and bottom. Those 4 properties let the developer move the element relatively to a specific position (depending on the chosen value for position).

By default, all HTML elements are unset, which means they cannot be moved from their position. left, right, top and bottom properties do nothing.

CSS

CSS - Positioning

position: relative; allows the element to be moved relatively to itself, meaning that left: 10px; will move it 10 pixels on the left.

position: fixed; allows the element to be positioned relatively to the browser, meaning that left: 10px; will place the element 10 pixels away from the left border of the browser. When using fixed position, the element is removed from the DOM, so other elements will be placed as if the fixed one didn't exist.

position: absolute; allows the element to be positioned relatively to its first positioned ancestor, meaning that left: 10px; will place the element 10 pixels away from the left border of the first ancestor which has position set to something else than unset. When using absolute position, the element is removed from the DOM, so other elements will be placed as if the absolute one didn't exist.

CSS

CSS - Positioning

position: sticky; behaves differently: a sticky item will behave like position: fixed, but only inside its container and only when the user scrolls outside the value defined by left, right, top or left.

See the Pen Positon Sticky to Bottom by Benjamin Vella (@Utopsia) on CodePen.

Original content.

CSS

CSS - Transitions

SOON

CSS

CSS - Transformations

SOON

CSS

CSS - Media Queries

SOON

HMTL, CSS, JS

JS part

JS

Introduction

Javascript is a programming language created in 1995 by Brendan Eich for Netscape. It was later submitted to Ecma International in order to have a standard specification for all browsers to conform to, and in 1997 the first ECMAScript specification was released.

Javascript is an object-oriented multi-paradigm language supporting event-driven, functional and imperative programming styles.

It is mainly used in web browsers to manipulate the content of a web page, but can also be run server side to perform all sort of tasks.

JS

Syntax - Variables

Typing in JS is dynamic (i.e. types are checked at runtime and types are associated with a value and not an expression) and weak (i.e. you don't need consistency in types, you can add a number and a string, or check if an array is true or false).

Since type mixing is possible and not checked before runtime, it can lead to problems and inconsistencies, but can also allow for very fast development.

There are 3 ways to declare a variable:
- var is the "old" way, the only one available before ES6 (EcmaScript 2015): var i = 5;
- let is the new "var". There are some differences between the 2, but we can ignore them for now: let i = 5;
- const add a constraint: the value cannot be modified: const i = 5;

JS

Syntax - Array

An array is a collection of elements. In JS, you can define an array by using [ ] : let myArray = [1, 2, 3];. Since JS is object-oriented, everything can be defined as an object. So technically you can declare an array by using the constructor of the Array class: let myArray = new Array(1, 2, 3);. let myArray = []; // We can reassign a new value to our variable: myArray = [1, 2]; // To add an element at the end of the list, use .push: myArray.push(3); // At this point myArray is [1, 2, 3]. To add an element at the beginning of the list, use .unshift: myArray.unshift(0); // At this point myArray is [0, 1, 2, 3]. To remove the element at the beginning of the list, use .shift: myArray.shift(); // At this point myArray is [1, 2, 3]. To remove the element at the end of the list, use .pop: myArray.pop(); // At this point myArray is [1, 2]. To get/set an element of the array, use [index]: myArray[1] = 5; // At this point myArray is [1, 5]. Don't forget that indexes start at 0, that's why myArray[1] replaced the second element. If you want to copy a part of your array, see .slice. If you want to replace some parts of the original array, see .splice.

JS

Syntax - Dict

A dict is a collection of key/value pairs. In JS, you can define a Dict by using { } : let myDict = { a: 5, b: 10 };. let myDict = {}; // To add a key/value pair in the dict, use [ ]: myDict["a"] = 2; // myDict is now {a: 2} // You can also use . to add an element: myDict.b = 4; // myDict is now {a: 2, b: 4} // To access a key, it's the same: let valueOfb = myDict.b;
let valueOfbTheOtherWay = myDict["b"];
// To delete a key, use delete: delete myDict.a; // myDict is now {b: 4}

JS

Syntax - Function as Function

A function can be considered for 2 use cases. In this first case, we will consider the standard way of using functions. To define a function, use the "function" keyword: function a() { ... }
// Or: let a = function() { ... }
// To call a function, type its name and add ( ): a(); // If the function should take arguments, add them to the declaration: function a(arg1, arg2) { ... }
...
a(3, 17);
// If the function should return a result, use the "return keyword": function mult(arg1, arg2) { return arg1 * arg2; }
...
let result = mult(3, 17);

JS

Syntax - Function as Class

A function can also be a class: function myClass() { ... }
...
let myInstance = new myClass();
// To store variable in your object, use "this" keyword: function myClass(arg1, arg2) {
    this.sum = arg1 + arg2;
}
...
let myInstance = new myClass(38, 13);
let additionResult = myInstance.sum;
// A function can also be part of another function: function myClass(arg1, arg2) {
    this.x = arg1;
    this.y = arg2;
    this.divide = function() { return this.x / this.y; }
}
...
let myInstance = new myClass(765, 15);
...
let result = myInstance.divide();

JS

Syntax - Conditions

To execute a code only in certain cases, you need to use a conditional instruction. // The most common is the if statement: if (condition) { ... } // If you have different conditions to test, use else if: if (condition) { ... }
else if (otherCondition) { ... }
// If you have a default code, use else: if (condition) { ... }
else if (otherCondition) { ... }
else { ... }
// For a short if-else, you can use the ternary operator: let result = condition ? ... : ...

A condition is an expression which is either True or False. It can be a variable (in JS, everything is considered True, except: 0, null, undefined, "", and NaN), a comparaison (<, <=, >, >=, ==, !=) or a composition of variables and comparisons (a && b is True only if both a and b are True ; a || b is True if a and/or b is True).

JS

Syntax - Looping

You often need to loop through collections to find compute the result you need. There are many way of doing that in js: let myArray = [3, 5, 3, 4];
let myDict = { x: 1, y: 7 };
// The classic for(init;condition;iteration) loop: let sum1 = 0;
for(let i=0 ; i < myArray.length ; i++) {
    sum1 += myArray[i];
}
// On arrays, we can use the for...of loop: let sum1 = 0;
for(let value of myArray) {
    sum1 += value;
} It is also possible to use forEach.
// On Dictionaries, we can use the for...in loop: let sum1 = 0;
for(let key in myDict) {
    sum1 += myDict[key];
} It is also possible, when working on dict, to use Object.keys(myDict) to get an array containing all keys of myDict and Object.values(myDict) to get an array containing all the values of myDict (and loop using for...of).

JS

DOM

When a browser loads an HTML page, it recreates the tree corresponding to the page. This tree is called the Document Object Model (DOM). Doing so allow developers to easily manipulate the HTML by using built-in methods instead of navigating through the HTML code by hand.

This DOM is accessible via the document object. It contains many useful functions, but for now we will focus on the ones allowing to search for a specific node.

- To retrieve an HTML element given its id, use document.getElementById()
- To retrieve an HTML element given one of its classes, use document.getElementsByClassName()
- To retrieve an HTML element given its tag, use document.getElementsByTagName()
- If you don't have just one attribute, you can use a full CSS selector document.querySelector()
Note 1: getElementById and querySelector returns only 1 Node whereas the other methods return a list of all nodes corresponding to the criterium Note 2: If you want to retrieve all the elements corresponding to a given selector, you can use document.querySelectorAll()

JS

DOM

The objects returned by the methods on the previous slide are of type Element, which contains many useful properties and methods to manipulate it.

Properties:
- Element.attributes gives you the list of attributes assigned to the Element
- Element.className gives you the class of the Element
- Element.id gives you the id of the Element
- Element.tagName gives you the tag of the Element
- Element.innerHTML contains the entirety of the HTML contained in it.
A fast way to remove all content from a node is to set innerHTML to an empty string: Element.innerHTML = "";

Methods:
- addEventListener() but we will talk about it later
- animate() allows to create animation easily (slide changes in this page are made with animate).
- append() lets you add another Element as child of the current one.
- getBoundingClientRect() gives you the position of the Element relative to the viewport.
- getElement(s)By*, querySelector* applied not to the entire page but to the descendents of current Element.

JS

CSSOM

The CSS Object Model follows more or less the same concept as the DOM (except its construction is way more complex): it creates a tree with all the styles applied to the Elements.

To modify the CSS of an Element, first find it, and then change its style attribute: HTML:
<p id="myParagraph">Hello World</p>

JS:
let elem = document.getElementById("myParagraph");
elem.style.color = "blue";

If the CSS property is usually written in kebab-case (background-color for instance), write it in camelCame inside the style attribute ("backgroundColor").

JS

Events

An important feature of JavaScript is to allow Event-oriented programming, which means that instead of following a pre-defined flow, code can be executed as a response to an event triggered by the user's actions.

There are a lot of Events which can be triggered. The most often used are:
- "load" triggered when the whole page has loaded.
- "mousemove" triggered when the user moves the mouse.
- "click" triggered when the user clicks.
- "keydown" or "keyup" triggered when the user press (or release) a key from the keyboard.

// To listen to an event, you need to call addEventListener() on an Element: let button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function(event) { console.log("button has been clicked !") });

If you need to listen to the event everywhere on the page, you can use window.addEventListener()

JS

Events

If you need longer code to be executed when an event triggers, you may set a function to be called:

// Call myMethod(event) when a button is clicked: let button = document.getElementsByTagName("button");
button.addEventListener("click", myMethod);
...
function myMethod(event) { ... }

The event argument automatically sent to the handler changes slightly depending on the event (for instance, a click event will contain the mouse position and a keypress event will contain the char code of the key being pressed). However, some properties will be present in any case.

function myMethod(event) {
    // We can access the HTML element on which the event has been triggered:     console.log(event.target);
    // We can stop the event from propagating to other triggered elements:     event.stopPropagation();
    // We can even stop the element to perform its natural behavior:     event.preventDefault();
}

JS

Cookies

Before GDPR, cookies were an invisible tool used to optimize navigation by storing the users' preferences on their PC.
Since GDPR, cookies are a visible constraining tool used to optimize navigation by storing the users' preferences on their PC.

When a user leaves a website, the website looses all information about the actions the user performed on the front side. Storing information on the user's PC is an easy way to remember what the user did so that everything can be configured as the user likes for the next visit.

There are 3 ways to store information on the user's PC: Cookies, localStorage, and sessionStorage. GDPR regulations concerns the first 2 (sessionStorage is not concerned because as its name implies, stored information are destroyed when the user ends the session).

We won't talk about sessionStorage as it manipulates exactly the same object as localStorage (same properties and methods).

JS

Cookies vs localStorage

The main difference between cookies and localStorage is that whenever the browser requests a page, cookies are automatically added to the HTTP request. This means that you should use cookies only if the stored information will be used by your file server. If that's not the case, you should use localStorage, which has more or less the same features but is not automatically sent.

To create a cookie associated to the key "myKey", use document.cookie:
document.cookie = "myKey=myValue; expires=Wed, 23 Sep 2022 23:59:59 UTC; path=/";
Note that it is not a normal string, just a shortcut to write a cookie: if you overwrite document.cookie (document.cookie = "myKey2=myValue2; expires=Wed, 23 Sep 2022 23:59:59 UTC; path=/"; for instance), the browser will just create another cookie associated to the key "myKey2".

To delete the cookie associated to the key "foo", simply set its expiration date in the past:
document.cookie = "foo=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

JS

localStorage

Localstorage is way easier to manipulate:
- To store a key/value, use localStorage.setItem(key, value);.
- To retrieve value associated to a key, use localStorage.getItem(key);.
- To delete a key/value pair, use localStorage.removeItem(key);.
- To delete all key/value pairs, use localStorage.clear();.

Storage works more or less like an object (or a dict), so you're not forced to use getItem and setItem, you can manipulate the storage like any other object (localStorage.myKey = "myValue" for instance).

localStorage is actually a property of window, but window's properties can be accessed without the need to use window.property. That being said, you CAN use it.

You can only store strings in the localStorage. If you need to store any other object, you can use JSON.stringify(myObject) to get a string representation of that object, and then use JSON.parse(myString) to get back the object. JSON (JavaScript Object Notation) is the most common way of describing objects in web (partly because JS converts it really easily).

JS

Networking

A lot of use cases require calling external servers:
- Security and confidentiality (login, private messages, ...).
- Codebase too heavy (millions of lines of code).
- Processing too long on user's computer (image processing, IA, ...).

To call an external server, you need a URL to target, the port the server listens to, and which protocol to use (HTTP(s), FTP, SSH, ...).

Most of the time, to communicate with a web application, the HTTP protocol will be used. There are many ways to create a server based on HTTP, but the easiest to manipulate (and so the most used) is REST, which adds a layer to the requests (GET, POST, DELETE, ...).

We will see 2 ways to communicate with a REST API in JS.

JS

Networking - XMLHttpRequest

Historically, XMLHttpRequest was used to call distant servers. // First, call the constructor. let xhr = new XMLHttpRequest(); // Then open a connection to a URL with the right method. xhr.open('GET', 'myapiserver.com/login'); // We can now send the request. xhr.send(); // Create a callback to be called when the response is received from the server. xhr.onload = function() { }

Do not be mistaken by the name of the class, it is not used to request XML (it can, but it is more widely used).

JS

Networking - Fetch

More recently, another JS API has been developed to call external server: Fetch // To send GET request on the standard HTTP port (80), default values work well: fetch('http://mywebsite.com/me') // Fetch returns a Promise .then(function(response) {}); // We can of course change the options if need be. fetch('http://mywebsite.com/me', {
    method: "POST",
    headers: { 'Content-Type': "application/json" },
    body: JSON.stringify(data)
}).then(function(data) {
    console.log(data);
});

JS

Networking - Why 2 ?

In most languages (may them be compiled or interpreted), there is an authority (official or not) responsible for building a tool so that the computers can execute the code.

In HTML, CSS, and JS, it is a bit more complex: it is the browsers' responsibility to build their own Engines to transform HTML/CSS/JS in websites.

The visitors can use any of them, even the ones which are not up-to-date to the latest standards. That's why you may still see an old JS module being used even though a better one has been created.

To help us know what is implemented in which browser, a website exists: caniuse.

NB: Transpilers (such as Babel) are capable of converting EcmaScript's latest standards in classic JS working on all browsers.

JS

NodeJs

Executing JS on a browser works well, but is limited: you cannot access files or run commands outside the browser. Problem is: natively, Operating Systems have no tools to execute JavaScript Code, because the JS engines are possessed in majority by browsers.

That is where NodeJs enters. It is a CLI built over V8 (Google Chrome's JavaScript Engine). Thanks to its use of V8, NodeJs is able to execute JS code, and since it's not a browser, it allows different features (to manipulate files on the computer for instance).

We can create REST servers in many languages, and JS is part of the list. One of the main advantages is that having a JS server ease a lot the communications since it's the same language on both side of the call.

JS

NodeJs - basic server

NodeJS possess many modules (native and non-native but free). Downloading a module is as easy as "npm install moduleName" ; adding a module to a JS script is done in one line by "const name = require(moduleName);", and then all the features of the module are available.

To create a server using nodeJs, the base element is the http module, and its createserver method: const http = require('http');
http.createServer(function(request, response) {
    ...
}).listen(8001);
8001 can be replaced by any open port on the machine.

http.createServer method takes 1 argument: a callback, which is a function that will be called every time a request is received by the server.
This callback function takes 2 arguments:
- request, which contains all the information about the request (url, method, headers, ...).
- response, which contains methods to send an information back to the client (statusCode, headers, data).

JS

NodeJs - request

Request is a js object containing the data sent by the user when requesting a resource on the server.

const http = require('http');
http.createServer(function(request, response) {
    // URL     request.url     // Method (GET, POST, PUT, DELETE, OPTIONS, ...)     request.method     // Headers     request.headers     // Body     let body = "";
    request.on('data', (chunk) => {body += chunk}
    request.on('end', () => { ... });
}).listen(8001);

JS

NodeJs - response

Response is a js object containing methods and data to send to the client.

const http = require('http');
http.createServer(function(request, response) {
    // Status code     response.statusCode = 418;     // Other headers     response.setHeader('content-Type', 'text/HTML');     // Body     response.end(data);
}).listen(8001);

JS

NodeJs - File manipulation

A native module allows the developer to manipulate files on the system. This module is fs (which stands for FileSystem). This module contains a lot of methods and options, but let's see the basics:

const fs = require('fs');
let data = "lorem ipsum dolor sit amet..."
// Write the content in a file fs.writeFile("myFile.txt", data, (error) => {
    if (error) { // do something. }
});
// Read a file let fileName = "myFile.txt";
fs.readFile(pathName, function(error, data) {
    if (error) { // do something. }
    else { // use data. }