An introduction to Frontend - 2020 Edition

An introduction to Frontend - 2020 Edition

This is an introduction to Frontend.

The course covers:
- HTML, CSS and Javascript (ES6) basics
- DOM manipulation with Vanilla JS
- Dependency management with NPM
- Task runner (e.g. Parcel)
- CSS preprocessor (e.g. Scss)

All slides have been prepared and used by me while teaching a course on Frontend basics.

Check out the repository (https://git.io/vb8Ay) and the final result (https://git.io/fjmCg).

Cda625b443cb7261a67f6dafc043439c?s=128

Marco Montalbano

October 26, 2019
Tweet

Transcript

  1. AN INTRODUCTION TO FRONTEND 1 AN INTRODUCTION TO FRONTEND Marco

    Montalbano
  2. GOAL AN INTRODUCTION TO FRONTEND 2 https://git.io/fjmCg

  3. AN INTRODUCTION TO FRONTEND 3 HTML

  4. HTML AN INTRODUCTION TO FRONTEND 4 • The acronym “HTML”

    stands for Hypertext Markup Language • It is not a programming language • It is a markup language which describes the structure of a web page semantically • It describes how to lay out the content of a web page using HTML elements called tags • It tells the browser what to display.
  5. TAG AN INTRODUCTION TO FRONTEND 5 • Each tag has

    a defined meaning • It can contain other tags • They are enclosed in angle brackets: <p> • Usually tags are made up of two elements: a "start tag" <p> and an "end tag" </p> • The start tag may include attributes within the tag <SPAN key="value"> testo </SPAN> void elements ( https://bit.ly/void-elements ) <INPUT key="value">
  6. TAGS AN INTRODUCTION TO FRONTEND 6 <html> - <head> -

    <body> base structure of an HTML document <!DOCTYPE html> <html> <head> … </head> <body> ... </body> </html> <meta> embedded in <head> tag metadata are not displayed on the page but are used by browsers or search engines <meta charset="utf-8"> <meta name="description" content="Page description."> <meta name="twitter:card" content="summary"> <title> embedded in <head> tag page title <title>title is visible inside the browser tab</title> <!DOCTYPE html> is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in <!DOCTYPE html> <html> …
  7. TAGS AN INTRODUCTION TO FRONTEND 7 <div> - <section> defines

    a division or a section in an HTML document <div> <div>this is a section</div> </div> <span> is a generic inline container for phrasing content this <span>text is on the</span> same line this text is on the same line <p> paragraph <p>this is a paragraph</p><p>this is a paragraph</p> this is a paragraph this is a paragraph <a> link link to <a href="https://www.google.com">google</a> link to google
  8. AN INTRODUCTION TO FRONTEND 8

  9. AN INTRODUCTION TO FRONTEND 9 HEADER HERO CONTENT FOOTER ARTICLE

    ARTICLE ARTICLE
  10. TAGS AN INTRODUCTION TO FRONTEND 10 <h1> - <h2> -

    <h…> - <h6> heading <h1>Title h1</h1> <h2>Title h2</h2> <h3>Title h3</h3> <h4>Title h4</h4> <h5>Title h5</h5> <h6>Title h6</h6> Title h1 Title h2 Title h3 Title h4 Title h5 Title h6 <ol> - <li> ordered list <ol> <li>first item</li> <li>second item</li> </ol> 1. first item 2. second item <ul> - <li> unordered list <ul> <li>first item</li> <li>second item</li> </ul> • first item • second item <table> - <tr> - <td> table – row – cell <table> <tr> <td>cell A1</td> <td>cell A2</td> </tr> </table> cell A1 cell A2
  11. TAGS – VOID ELEMENTS AN INTRODUCTION TO FRONTEND 11 <input>

    text input <input type="text" name="firstname"> <br> line break this text contains<br>a line break this text contains a line break <hr> defines a thematic break this is a topic <hr> this is a different topic this is a topic this is a different topic <img> image <img src="assets/html5.jpg">
  12. None
  13. ATTRIBUTES AN INTRODUCTION TO FRONTEND 13 <a> href contains a

    URL or a URL fragment that the hyperlink points to link to <a href="https://www.google.it">google</a> <img> the attribute src is mandatory and defines the image URL <img src="assets/html5.jpg" alt="" title=""> <input> - name and value are submitted with the form data - type specifies the type <input> element to display <input type="text" name="firstname" value=""> <TAG> all tags can have an id and a class <div id="my-id" class="my-class my-second-class">text</div>
  14. • MDN web docs – https://developer.mozilla.org/en/docs/Web/HTML • Codecademy – https://www.codecademy.com/learn/learn-html

    • W3C – https://www.w3.org/html AN INTRODUCTION TO FRONTEND 14 REFERENCES
  15. AN INTRODUCTION TO FRONTEND 15 HTML in action https://bit.ly/fe4b-html

  16. AN INTRODUCTION TO FRONTEND 16 CSS

  17. CSS AN INTRODUCTION TO FRONTEND 17 • The acronym “CSS”

    stands for Cascade Style Sheet • It is not a programming language • Used for describing the presentation of an HTML document • Defines fonts, layout, colors, etc. of the whole page and single elements • It tells the browser how to display informations.
  18. CSS AN INTRODUCTION TO FRONTEND 18 a web page is

    styled according to a set of style rules div { color: blue; font-size: 15px; } selector property value
  19. SELECTORS https://mzl.la/33MQNR4 AN INTRODUCTION TO FRONTEND 19 in order to

    identify which elements are affected by style rules we need a selector 1. type selectors div { … } #policy-section { … } 2. ID selectors .small { … } 3. class selectors [title] { … } [title="open"] { … } 4. attribute selectors <section id="policy-section" class="container"> <div>Text here</div> <div class="small">Small text here</div> <a class="small" title="open">Click me</a> </section>
  20. #elm-id div#elm-id element with id "elm-id" <div> with id "elm-id"

    .elm-class div.elm-class elements with class "elm-class" all <div> with class "elm-class" div div, span div span div > span all <div> <div> and <span> <span> nested in <div> <span> children of <div> grouping and combine selectors SELECTORS AN INTRODUCTION TO FRONTEND 20 div:hover .error:focus all <div> on mouse-over elements with class “error” on focus #elm-id.elm-class element with id "elm-id" and class "elm-class"
  21. Position/Number-based :first-child :last-child :nth-child() :nth-of-type() Relational :not() :empty Link-related :link

    :visited :hover :active Input & link related :focus :enabled :disabled :checked :indeterminate :required :optional :target SELECTORS pseudo-classes https://mzl.la/3cVYN6v - https://css-tricks.com/pseudo-class-selectors/ AN INTRODUCTION TO FRONTEND 21 is a keyword added to a selector that specifies a special state of the selected element(s) Live Demo https://codesandbox.io/embed/pseudo-class-selectors-0xntp
  22. SELECTORS AN INTRODUCTION TO FRONTEND 22 just a more complex

    selector div.menu-bar li:hover > ul { color: blue; }
  23. PROPERTIES AN INTRODUCTION TO FRONTEND 23 color: background-color: background-image: #FF0000

    blue url("html5.png") font-family: font-size: font-weight: font-style: Arial, sans-serif 14px bold italic text-align: text-shadow: text-decoration: text-decoration: center 1px 1px 1px blue line-through underline position: position: position: top: right: bottom: left: static relative absolute 10px -5px 3px 10px
  24. AN INTRODUCTION TO FRONTEND 24

  25. BOX MODEL AN INTRODUCTION TO FRONTEND 25 the CSS box

    model is essentially a box that wraps around every HTML element
  26. BOX MODEL AN INTRODUCTION TO FRONTEND 26 margin: 10px; margin:

    10px 15px; margin: 10px 15px 10px 10px; increases the element margin padding: 10px; padding: 10px 15px; padding: 10px 15px 10px 10px; padding-top: 10px; padding-right: 15px; … increases space around the border and content of the element border: 1px solid #F1F1F1; border-top: 2px solid #F1F1F1; adds a border around the element height: 150px; width: 50%; sets a width and a height to the element
  27. DISPLAY AN INTRODUCTION TO FRONTEND 27 every HTML element has

    a default display value depending on what type of element it is display: block; <div> and <p> are block elements. A block-level element always starts on a new line and takes up the full width available. <p>This is a paragraph</p> <p>This is another paragraph</p> display: inline; <a> does not start on a new line and only takes up as much width as necessary This <a>link</a> does not start on a new line and only takes up as much width as necessary.
  28. POSITION https://mzl.la/2MZAn0D AN INTRODUCTION TO FRONTEND 28 static relative absolute

    The position CSS property sets how an element is positioned in a document. The top, right, bottom, and left properties determine the final location of positioned elements.
  29. AWD vs RWD AN INTRODUCTION TO FRONTEND 29 ADAPTIVE WEB

    DESIGN multiple templates specific for each device RESPONSIVE WEB DESIGN a single design that adjusts to each device
  30. RESPONSIVE WEB DESIGN AN INTRODUCTION TO FRONTEND 30 • Rule

    1 – <meta name="viewport" content="width=device-width, initial-scale=1.0"> • Rule 2 – use % values instead of px • Rule 3 – define breakpoints using media query Media Query uses @media rule to include a set of CSS properties only if the specific condition is true .col { width: 100%; } @media (max-width: 768px) { .col { width: 50%; } }
  31. LAYOUT EVOLUTION https://bit.ly/css-layout-evolution AN INTRODUCTION TO FRONTEND 31 At the

    beginning the most sophisticated layout tool designers had was <table> … </table> .. and inline-block display: inline-block; Then we began to hack out layouts with complicated mixtures of absolute positioning, floats .. position: absolute; float: left; Flexbox & Grid Layout
  32. FLEXBOX https://mzl.la/2Ckg35E - https://css-tricks.com/snippets/css/a-guide-to-flexbox AN INTRODUCTION TO FRONTEND 32 it

    gives the container the ability to alter its items' width/height (and order) to best fill the available space .container { display: flex; flex-direction: row | row-reverse | column | column-reverse; } .container { display: flex; } .container { display: flex; flex-wrap: nowrap | wrap | wrap-reverse; } support for IE starts from 10*
  33. FLEXBOX https://mzl.la/2Ckg35E - https://css-tricks.com/snippets/css/a-guide-to-flexbox AN INTRODUCTION TO FRONTEND 33 justify-content

    align-items align-content support for IE starts from 10
  34. FLEXBOX https://mzl.la/2Ckg35E - https://css-tricks.com/snippets/css/a-guide-to-flexbox AN INTRODUCTION TO FRONTEND 34 align-self

    order flex-grow support for IE starts from 10
  35. FLEXBOX READ PLAY MORE AN INTRODUCTION TO FRONTEND 35

  36. GRID LAYOUT https://mzl.la/2q4aXYi - https://css-tricks.com/snippets/css/complete-guide-grid AN INTRODUCTION TO FRONTEND 36

    .container { display: grid; grid-template-columns: 25% 25% 25% 25%; grid-template-rows: auto; grid-template-areas: "header header header header" "main main . sidebar" "footer footer footer footer"; } .item-header { grid-area: header; ... } .item-main { grid-area: main; ... } .item-sidebar { grid-area: sidebar; ... } .item-footer { grid-area: footer; ... } support for IE starts from 10*
  37. GRID LAYOUT READ PLAY MORE AN INTRODUCTION TO FRONTEND 37

  38. TRANSITION AN INTRODUCTION TO FRONTEND 38 Transitions enable you to

    define the transition between two states of an element .cookie-policy { opacity: 1; transition: opacity 2s; } .cookie-policy.hidden { opacity: 0; }
  39. WHY “CASCADING” ? AN INTRODUCTION TO FRONTEND 39 the rule

    used is chosen by cascading down from the more general rules to the specific rule required selector # of ID # of CLASS # of TAG specificity #my-id 1 0 0 100 .my-class 0 1 0 10 li 0 0 1 1 ul li 0 0 2 2 li.my-class 0 1 1 11 <ul> <li id="my-id" class="my-class"></li> </ul> the most specific rule is chosen • with equal specificity, the last rule is chosen • style-inline rules out every other rule •
  40. WHERE DO I WRITE THIS? AN INTRODUCTION TO FRONTEND 40

    <style> not so bad, but avoid it anyway <style> span { color: blue; } </style> <link> load it from file new tag is embedded in <head> tag <link rel="stylesheet" href="style.css"> Style inline don’t try this at office nowhere this <span style="color: blue;">text is blue</span> style.css span { color: blue; } this text is blue
  41. AN INTRODUCTION TO FRONTEND 41 REFERENCES • MDN web docs

    – https://developer.mozilla.org/en/docs/Web/CSS • Codecademy – https://www.codecademy.com/learn/learn-css • W3C – https://www.w3.org/Style/CSS/Overview.en.html
  42. AN INTRODUCTION TO FRONTEND 42 CSS in action https://bit.ly/fe4b-css

  43. AN INTRODUCTION TO FRONTEND 43 JAVASCRIPT

  44. JAVASCRIPT AN INTRODUCTION TO FRONTEND 44 • It’s not an

    acronym • It is a scripting Object-Oriented language • Everything is an object (except null and undefined) • It is untyped • It is implemented client-side in web browsers • It is also implemented server-side with node.js • It makes web pages interactive • It’s an implementation of the EcmaScript standard https://developer.mozilla.org/en-US/docs/Web/JavaScript/About_JavaScript https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
  45. A re-introduction to JavaScript https://mzl.la/3fMBmxE AN INTRODUCTION TO FRONTEND 45

    JavaScript was created in 1995 by Brendan Eich while he was an engineer at Netscape. JavaScript was first released with Netscape 2 early in 1996. It was originally going to be called LiveScript, but it was renamed in an ill-fated marketing decision that attempted to capitalize on the popularity of Sun Microsystem's Java language — despite the two having very little in common. This has been a source of confusion ever since. Several months later, Microsoft released JScript with Internet Explorer 3. It was a mostly-compatible JavaScript work-alike. Several months after that, Netscape submitted JavaScript to Ecma International, a European standards organization, which resulted in the first edition of the ECMAScript standard that year. The standard received a significant update as ECMAScript edition 3 in 1999, and it has stayed pretty much stable ever since. The fourth edition was abandoned, due to political differences concerning language complexity. Many parts of the fourth edition formed the basis for ECMAScript edition 5, published in December of 2009, and for the 6th major edition of the standard, published in June of 2015.
  46. ECMAScript AN INTRODUCTION TO FRONTEND 46 timeline ES 6 June

    2015 This update adds significant new syntax for writing complex applications, including class declarations and ES6 modules. Other new features include iterators and for/of loops, Python-style generators, arrow function expression, binary data, typed arrays, new collections, promises, number and math enhancements, reflection, proxies and template literals for strings. ES 6 ES 9 June 2018 ES 1 June 1997 First edition. ES 1 ES 2 June 1998 Editorial changes to keep the specification fully aligned with ISO/IEC 16262 international standard. ES 2 ES 3 December 1999 Added regular expressions, better string handling, new control statements, try/catch exception handling, tighter definition of errors, formatting for numeric output ... ES 3 ES 5 December 2009 Adds "strict mode," a subset intended to provide more thorough error checking and avoid error-prone constructs. Adds some new features, such as getters and setters, library support for JSON, and more complete reflection on object properties. ES 5 ES 5.1 December 2011 This edition 5.1 of the ECMAScript standard is fully aligned with third edition of the international standard ISO/IEC 16262:2011. ES 5.1 ES 7 June 2016 The major standard language features include block-scoping of variables and functions, destructuring patterns (of variables), ... ES 7 ES 8 June 2017 Includes async/await constructions, which works using generators and promises. ES 8
  47. let and const names: • Can contain letters, numbers, $

    and _ • Can start with a letter, $ and _ • Are case-sensitive ( y and Y are two different variables ) VARIABLES and CONSTANTS https://bit.ly/mdn-js-let – https://bit.ly/mdn-js-const AN INTRODUCTION TO FRONTEND 47 support for IE starts from 11 let and const cannot be redeclared let age = 30; let age = 30; // syntax error const name = 'John'; const name = 'John'; // syntax error const cannot be reassigned let age = 30; age = 31; const name = 'John'; name = 'Marco'; // syntax error const must be initialized let age; age = 31; const name; // syntax error name = 'Marco';
  48. VARIABLES and CONSTANTS https://bit.ly/mdn-js-let – https://bit.ly/mdn-js-const AN INTRODUCTION TO FRONTEND

    48 let myNumber = 3 + 5; let myString = 'Hello' + ' ' + 'World!!'; let myArray = ['apple', 'lime', 3]; console.log( myArray[0] ); //Prints ‘apple’ let myObject = { name: 'John', age: 28 }; console.log(myObject.name); //Prints ‘John’ let myFloat = 3.5; let myFunction = function(num1, num2) { return num1 + num2; } support for IE starts from 11
  49. CONST rules of thumb AN INTRODUCTION TO FRONTEND 49 const

    myObject = { name: 'John', age: 28 }; // syntax error myObject = 'Just a string'; const myObject = { name: 'John', age: 28 }; // this is ok myObject.age = 31; const has immutable binding not immutability support for IE starts from 11
  50. you can also declare variable with var keyword VAR AN

    INTRODUCTION TO FRONTEND 50 if you need browser compatibility for non-modern browsers babeljs.io for the rescue But forget about it!
  51. FUNCTIONS https://mzl.la/2IEQd0C AN INTRODUCTION TO FRONTEND 51 • Usually is

    defined through keyword function followed by a name and ( ) • The name can contain letters, numbers, _ and $ (just like variables) • The ( ) can contain arguments separated by commas • Arguments can have a default value function add(num1, num2 = 10) { return num1 + num2; } const result = add(5, 5); //= 10 const add = function(num1, num2 = 10) { return num1 + num2; } no support for IE const result = add(6); //= 16
  52. ARROW FUNCTIONS https://mzl.la/3a9wMs6 AN INTRODUCTION TO FRONTEND 52 • Is

    a syntactically compact alternative to a regular function expression • Doesn’t have its own bindings to the this, arguments, super, or new.target keywords • Arrow functions can have either a "concise body" or the usual "block body". const result = add(5, 5); //= 10 const add =(num1, num2 = 10) => { return num1 + num2; } const result = add(6); //= 16 no support for IE const add = (num1, num2 = 10) => num1 + num2;
  53. BLOCK-LEVEL SCOPE AN INTRODUCTION TO FRONTEND 53 let age =

    31; console.log(age); // 31 if (true) { let age = 25; console.log(age); // 25 } console.log(age); // 31 function getValue(condition) { // myVariable doesn't exist here if (condition) { let myVariable = 5; } else { // myVariable doesn't exist here } // myVariable doesn't exist here } Variables declared using let or const keywords are block-level scoped A block is indicated by the { and } characters support for IE starts from 11
  54. ReferenceError: 'myVariable' is not defined console.log(myVariable); TEMPORAL DEAD ZONE AN

    INTRODUCTION TO FRONTEND 54 console.log(myVariable); let myVariable = 5; ReferenceError: Cannot access 'myVariable' before initialization A variable declared with either let or const cannot be accessed until after the declaration support for IE starts from 11
  55. COMPARISON OPERATORS https://mzl.la/2wCuFwX AN INTRODUCTION TO FRONTEND 55 3 ==

    3 == vs === A comparison operator compares its operands and returns a logical value based on whether the comparison is true true "3" == 3 true 3 === 3 true "3" === 3 false 3 >= 3 true 3 < 4 true
  56. for ( let step = 0; step < 5; step++

    ) { // Runs 5 times, with values of step 0 through 4. console.log('Walking east one step'); } for LOOPS AND ITERATION https://mzl.la/2KX0uUo AN INTRODUCTION TO FRONTEND 56 Loops offer a quick and easy way to do something repeatedly let i = 0; while (i < 5) { i += 1; console.log(i); }; while let i = 0; do { i += 1; console.log(i); } while (i < 5); do
  57. const array1 = ['a', 'b', 'c']; array1.forEach(function (element) { console.log(element);

    }); .forEach() ARRAY METHODS https://mzl.la/2N39dGy AN INTRODUCTION TO FRONTEND 57 Array object offer helper methods const array1 = [1, 2, 3]; const results = array1.map((value) => value * 2); .map() const array1 = [2, 3, 4]; const results = array1.filter(function (value) { return value % 2 === 0; }); .filter() support for IE starts from 9
  58. DESTRUCTURING ASSIGNMENT https://mzl.la/2CeK22j AN INTRODUCTION TO FRONTEND 58 Expression that

    makes it possible to unpack values from arrays, or properties from objects, into distinct variables. no support for IE console.log(name); // John console.log(age); // 28 const person = ['John', 28]; const [ name, age ] = person; ARRAY const person = { name: 'John', age: 28 }; const { name, age } = person; OBJECT const person = { name: 'John', age: 28 }; const printInfo =({ name, age }) => { console.log(name); // John console.log(age); // 28 } printInfo(person); USAGE WITH FUNCTIONS
  59. TEMPLATE STRINGS https://mzl.la/2DUepv9 AN INTRODUCTION TO FRONTEND 59 Multi-line strings

    and string interpolation features no support for IE const text = `This is a multi-line text`; const person = { name: 'John', age: 28 }; const text = `My name is ${ person.name }`;
  60. EXPORT / IMPORT https://mzl.la/3itzuMi - https://mzl.la/3kEU666 AN INTRODUCTION TO FRONTEND

    60 no support for IE export default { name: 'John', age: 28 }; EXPORT DEFAULT import person from './person.js'; IMPORT DEFAULT export const red = { name: 'red', hex: '#FF0000' } const green = { name: 'green', hex: '#00FF00' } const blue = { name: 'blue', hex: '#0000FF' } export { green, blue }; NAMED EXPORT import { red, green, blue } from './colors.js'; NAMED IMPORT import React, { useState } from 'react'; MIXED IMPORT
  61. AN INTRODUCTION TO FRONTEND 61 REFERENCES • MDN web docs

    – https://developer.mozilla.org/it/docs/Web/JavaScript • Codecademy – https://www.codecademy.com/learn/introduction-to-javascript • Nicholas C. Zakas - Understanding ES6 – https://leanpub.com/understandinges6/read
  62. AN INTRODUCTION TO FRONTEND 62 JAVASCRIPT & DOM

  63. DOM AN INTRODUCTION TO FRONTEND 63 DOM ( Document Object

    Model ) describes the HTML document as a tree structure wherein each node is an object • The document object represents your web page • Document is made up of nodes • Element nodes are html tags • The HTML DOM can be accessed with JavaScript
  64. DOM • JS FUNCTIONS AN INTRODUCTION TO FRONTEND 64 document.getElementsByTagName(

    'span' ) returns a collection of all elements in the document with the specified tag name, as a NodeList object document.getElementsByClassName( 'my-class' ) returns a collection of all elements in the document with the specified class name, as a NodeList object document.getElementsByName( 'email' ) returns a collection of all elements in the document with the specified name (the value of the name attribute), as a NodeList object document.querySelectorAll( '.my-class' ) returns a static NodeList representing a list of the document's elements that match the selector. <span class="my-class my-class-1">test</span> <span class="my-class my-class-2">test</span> <script> const element = document.querySelectorAll('.my-class'); // elements contains both spans. </script> document.getElementById( 'my-id' ) returns the element that has the ID attribute with the specified value <span id="my-id">test</span> <script> const element = document.getElementById('my-id'); </script> document.querySelector( '.my-class' ) returns the first Element within the document that matches the specified selector, or group of selectors. <span class="my-class my-class-1">test</span> <span class="my-class my-class-2">test</span> <script> const element = document.querySelector('.my-class'); // element contains the first span. </script>
  65. DOM • NODE PROPERTIES AN INTRODUCTION TO FRONTEND 65 firstChild

    - lastChild → Node object returns the first and last child node of the specified node <div id="my-id"><span>Hello</span> <b>World</b>!</div> <script> const element = document.getElementById('my-id'); console.log( element.firstChild ); //= <span> console.log( element.lastChild ); //= <b> </script> innerHTML returns the HTML content of an element <div id="my-id">Hello <b>World</b>!</div> <script> const element = document.getElementById('my-id'); console.log( element.innerHTML ); //= Hello <b>World</b>! </script> textContent returns the textual content of the specified node, and all its descendants <div id="my-id">Hello <b>World</b>!</div> <script> const element = document.getElementById('my-id'); console.log( element.textContent ); //= Hello World! </script> childNodes → NodeList object returns a collection of a node's child nodes <div id="my-id"><span>Hello</span> <b>World</b>!</div> <script> const element = document.getElementById('my-id'); console.log( element.childNodes ); //= [ <span>, <b> ] </script>
  66. DOM • EVENTS AN INTRODUCTION TO FRONTEND 66 dispatchEvent dispatches

    an Event at the specified element (EventTarget - DOM interface). <button id="my-button">Greet!</button> <script> const element = document.getElementById('my-button'); const clickEvent = new Event('click'); element.dispatchEvent(clickEvent); </script> addEventListener sets up a function (callback) that will be called whenever the specified event is delivered to the target. <button id="my-button">Greet!</button> <script> const element = document.getElementById('my-button'); element.addEventListener('click', function(event) { console.log('Hi all!'); console.log(event.target); //= <button id="my-button"> ... }); </script>
  67. function f1() { return this; } f1() === window; //=

    true THIS https://mzl.la/2Idy8rl AN INTRODUCTION TO FRONTEND 67 In most cases, the value of this is determined by how a function is called var o = { prop: 37, f2: function () { return this.prop; } }; console.log( o.f2() ); //= 37 var elm = document.getElementById('my-id'); elm.addEventListener('click', f3); function f3(e) { console.log( this === e.currentTarget ); //= true } this is set to the element the event fired from Remember! Arrow functions doesn’t have the THIS keyword.
  68. const myPromise = new Promise(function (resolve, reject) { const result

    = doSomethingTimeConsuming(); resolve(result); }); PROMISE https://mzl.la/2phpuPU AN INTRODUCTION TO FRONTEND 68 The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. myPromise.then(function (result) { console.log(result); }); myPromise.catch(function (error) { console.warn(error); }); no support for IE
  69. FETCH https://mzl.la/2OLg6yA AN INTRODUCTION TO FRONTEND 69 The Fetch API

    provides an interface for fetching resources const responsePromise = fetch('https://next.json-generator.com/api/json/get/VylGdfytP'); const jsonPromise = responsePromise.then(function (response) { return response.json(); }); jsonPromise.then(function (json) { console.log(json); }); no support for IE
  70. POLYFILL AN INTRODUCTION TO FRONTEND 70 DOMTokenList.prototype.toggle = function (name,

    force) { var exists = this.contains(name); if (exists === force) { return force; } if (exists) { this.remove(name); } else { this.add(name); } return !exists; }; A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it. https://mzl.la/2P2Q7Tm no support for IE support for IE starts from 10 const element = document.querySelector('.element'); let isVisible = true; element.classList.toggle('visible', isVisible);
  71. WHERE DO I WRITE THIS? AN INTRODUCTION TO FRONTEND 71

    <script>…</script> not so bad, but avoid it in most cases <script> alert('Hello World!'); </script> <script src="…"></script> load it from file new tag is embedded at the end of <body> tag <script src="application.js"></script> Script inline don’t try this at office nowhere <a onclick="alert('Hello World!');">greet</a>
  72. AN INTRODUCTION TO FRONTEND 72 REFERENCES • MDN web docs

    – https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model • Codecademy – https://www.codecademy.com/courses/javascript-beginner-en-gwcYv/0/1 • What is the DOM? – https://css-tricks.com/dom/
  73. AN INTRODUCTION TO FRONTEND 73 JAVASCRIPT & DOM in action

    https://bit.ly/fe4b-js
  74. AN INTRODUCTION TO FRONTEND 74 SASS - SCSS

  75. SASS - SCSS https://sass-lang.com AN INTRODUCTION TO FRONTEND 75 •

    It is a CSS pre-processor • It extends CSS adding variables, mixins, functions and more • It make CSS more maintainable over time • It can be converted to CSS using different tools
  76. CSS = SCSS AN INTRODUCTION TO FRONTEND 76 • Same

    syntax • Same semantics SCSS = CSS + extensions • Nesting • Variables • Partials and Import • Mixins • Extend/Inheritance • Operators
  77. SCSS • NESTED RULES AN INTRODUCTION TO FRONTEND 77 #header

    { color: black; } #header > .navigation { font-size: 12px; } #header a { color: blue; } #header a:hover { color: green; } CSS #header { color: black; > .navigation { font-size: 12px; } a { color: blue; &:hover { color: green; } } } SCSS
  78. SCSS • NESTED RULES • @media AN INTRODUCTION TO FRONTEND

    78 .component { width: 100%; } .component .blue { color: blue; } @media (max-width: 768px) { .component { width: 50%; } } CSS .component { width: 100%; .blue { color: blue; } @media (max-width: 768px) { width: 50%; } } SCSS
  79. SCSS • VARIABLES AN INTRODUCTION TO FRONTEND 79 • Begin

    with “$” dollar signs • Common property values can be written only once • You can change multiple values changing just one code line • Variable names can use hyphens “-” and underscores “_” interchangeably $border-color: #FFFFFF; $my-border: 1px solid #FFFFFF; $my-border: 1px solid $border-color; $size: 100px;
  80. SCSS • VARIABLES AN INTRODUCTION TO FRONTEND 80 .component-header {

    color: #FFFFFF; border-bottom: 1px solid #FFFFFF; } .component-footer { color: #FFFFFF; background-color: #FF0000; } .another-component { color: #FF0000; } CSS $color-1: #FFFFFF; $color-2: #FF0000; .component-header { color: $color-1; border-bottom: 1px solid $color-1; } .component-footer { color: $color-1; background-color: $color-2; } .another-component { color: $color-2; } SCSS
  81. • Suppose we have two TAGs with a total width

    of 1000px • One must be ¾ of the other SCSS • MATH OPERATIONS AN INTRODUCTION TO FRONTEND 81 #content { width: 750px; } #sidebar { width: 250px; } CSS $width: 1000px; $contentWidth: $width * (3 / 4); $sidebarWidth: $width - $contentWidth; #content { width: $contentWidth; } #sidebar { width: $sidebarWidth; } SCSS
  82. SCSS • MATH FUNCTIONS AN INTRODUCTION TO FRONTEND 82 •

    ceil( 2.4 ) → 3 • floor( 2.6 ) → 2 • round( 1.67 ) → 2 • percentage( 0.5 ) → 50% • sqrt( 25px ) → 5px • abs( -15px ) → 15px • min( 5, 10 ) → 5 • max( 5, 10 ) → 10 SCSS • COLOR FUNCTIONS • rgb( 90, 129, 32 ) → #5a8120 • red( #5a8120 ) → 90 • green( #5a8120 ) → 129 • blue( #5a8120 ) → 32 • lighten( #80e619, 20% ) → #b3f075 • darken( #80e619, 20% ) → #4d8a0f
  83. SCSS • INTERPOLATION SYNTAX AN INTRODUCTION TO FRONTEND 83 You

    can use variables in selectors and property names using #{} interpolation syntax $name: "foo"; $attr: "border"; p.#{$name} { #{$attr}-color: blue; } SCSS p.foo { border-color: blue; } CSS
  84. Using @extend lets you share a set of CSS properties

    from one selector to another SCSS • @extend AN INTRODUCTION TO FRONTEND 84 .success { color: green; } .element-1 { @extend .success; font-weight: bold; } .element-2 { @extend .success; } SCSS .success, .element-1, .element-2 { color: green; } .element-1 { font-weight: bold; } CSS
  85. A placeholder class is a special type of class that

    only prints when it is extended SCSS • @extend AN INTRODUCTION TO FRONTEND 85 %message-shared { color: green; } %another-message { color: blue; } .element { @extend %message-shared; } SCSS .element { color: green; } CSS
  86. • Used to define a group of properties and use

    them later on • Parametric mixins are by all means functions SCSS • @mixin AN INTRODUCTION TO FRONTEND 86 @mixin border-radius($radius: 10px) { -moz-border-radius: $radius; border-radius: $radius; } #header { @include border-radius(4px); } SCSS #header { -moz-border-radius: 4px; border-radius: 4px; } CSS
  87. SCSS • @mixin PRO AN INTRODUCTION TO FRONTEND 87 @mixin

    border-radius($radius: 10px) { @if ($radius == 20px) { $radius: $radius * 2px; } -moz-border-radius: $radius; border-radius: $radius; } #header { @include border-radius(20px); } SCSS #header { -moz-border-radius: 40px; border-radius: 40px; } CSS
  88. @import "variable"; @import "header"; @import "footer"; ... application.scss SCSS •

    IMPORT AN INTRODUCTION TO FRONTEND 88 You can import .scss files inside other .scss files @import "this-is-valid"; .header { color: $color-1; } _header.scss .footer { color: $color-2; } _footer.scss $color-1: #FFFFFF; $color-2: #FF0000; ... _variables.scss
  89. $var: red; #header { .white { $var: white; color: $var;

    // white } color: $var; // red } SCSS • SCOPE AN INTRODUCTION TO FRONTEND 89 Variables and mixins are first looked for locally, and if they aren't found, the compiler will look in the parent scope, and so on $var: red; #header { .white { $var: white; color: $var; // white } color: $var; // red } $var: blue; #footer { color: $var; // blue } #header { color: red; } #header .white { color: white; } #footer { color: blue; } CSS SCSS
  90. AN INTRODUCTION TO FRONTEND 90 https://www.sassmeister.com

  91. 1 npm install -g sass HOW DO I COMPILE IT?

    AN INTRODUCTION TO FRONTEND 91 -g installs the specified package as a global package. It is useful if you want to use it as a command line tool sass input.scss output.css 2
  92. AN INTRODUCTION TO FRONTEND 92 NODE.JS

  93. NODE.JS AN INTRODUCTION TO FRONTEND 93 • Node.js is a

    JavaScript runtime built on Chrome's V8 JavaScript engine. • V8 is the JavaScript execution engine built for Google Chrome and open-sourced by Google in 2008. • Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient • It executes JavaScript code server-side • There are a lot of applications today that use Node.js
  94. AN INTRODUCTION TO FRONTEND 94

  95. AN INTRODUCTION TO FRONTEND 95

  96. NPM https://www.npmjs.com AN INTRODUCTION TO FRONTEND 96 “Node.js' package ecosystem,

    npm, is the largest ecosystem of open source libraries in the world” https://nodejs.org NPM ≈ Maven ≈ Composer ≈ Bundler ≈ … Java PHP Ruby
  97. package.json is used to give information to npm that allows

    it to identify the project as well as handle the project's dependencies. devDependencies are dependencies not required for normal operation, but required/recommended if you want to patch or modify the project ( unit test, lint, builder, ecc. ). dependencies field is used to list all the dependencies of your project that are available on npm. When someone installs your project through npm, all the dependencies listed will be installed as well. NPM https://docs.npmjs.com/files/package.json AN INTRODUCTION TO FRONTEND 97 { "name": "project-name", "description": "project-desc", "version": "1.0.0", "license": "MIT", "dependencies": { "express": "^4.17.1" }, "devDependencies": { "mocha": "^6.2.2" }, "scripts": { "test": "mocha", "build": "webpack" } } package.json
  98. NPM https://docs.npmjs.com/cli-documentation AN INTRODUCTION TO FRONTEND 98 npm install -

    npm update installs a package, and any packages that it depends on npm prune removes packages that are not listed on the parent package's dependencies list npm install <package-name> installs the specified package and adds it to the package.json { "name": "project-name", "description": "project-desc", "version": "1.0.0", "license": "MIT", "dependencies": { "express": "^4.17.1" }, "devDependencies": { "mocha": "^6.2.2" }, "scripts": { "test": "mocha", "build": "webpack" } } package.json
  99. NPM https://docs.npmjs.com/misc/scripts AN INTRODUCTION TO FRONTEND 99 { "name": "project-name",

    "description": "project-desc", "version": "1.0.0", "license": "MIT", "dependencies": { "express": "^4.17.1" }, "devDependencies": { "mocha": "^6.2.2" }, "scripts": { "test": "mocha", "build": "webpack" } } package.json npm test this runs a package’s “test” script, if one was provided. scripts section The “scripts” property is a dictionary containing script commands that are run at various times in the lifecycle of your package. You can also trigger them manually. npm run build this runs a package’s “build” script, if one was provided.
  100. NPM • node_modules AN INTRODUCTION TO FRONTEND 100 npm install

    { "name": "project-name", "description": "project-desc", "version": "1.0.0", "license": "MIT", "dependencies": { "express": "^4.17.1" }, "devDependencies": { "mocha": "^6.2.2" }, "scripts": { "test": "mocha", "build": "webpack" } } package.json A folder with name node_modules is created. This folder contains all downloaded dependencies. You don’t need to commit and push this folder, so remember to add it to .gitignore file.
  101. HOW DO I INSTALL NODE.JS? AN INTRODUCTION TO FRONTEND 101

  102. WHERE ARE PACKAGES? AN INTRODUCTION TO FRONTEND 102

  103. AN INTRODUCTION TO FRONTEND 103 PARCEL

  104. PARCEL AN INTRODUCTION TO FRONTEND 104 Parcel is a Web

    Application Bundler. Its main features set includes: • zero configuration • assets bundling (HTML, CSS, JS) • automatic transforms using Babel • caching and parallel processing for faster builds • hot module replacement
  105. HOW DO I INSTALL PARCEL? AN INTRODUCTION TO FRONTEND 105

    npm install -D parcel-bundler 1 -D installs the specified package as a dev dependency
  106. PARCEL SCRIPTS https://en.parceljs.org/getting_started.html AN INTRODUCTION TO FRONTEND 106 1 {

    "name": "an-introduction-to-frontend", "description": "An introduction to Frontend", "version": "1.0.0", "license": "MIT", "devDependencies": { "parcel-bundler": "~1.12.4" }, "scripts": { "start": "parcel index.html", "build": "parcel build index.html" } } package.json
  107. AN INTRODUCTION TO FRONTEND 107 from https://bit.ly/fe4b-js to https://github.com/marcomontalbano/an-introduction-to-frontend Let’s

    Try 107
  108. AN INTRODUCTION TO FRONTEND 108 GitHub https://github.com/marcomontalbano/an-introduction-to-frontend Thank You! Lorem

    ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Project Name