SlideShare a Scribd company logo
Java script
Who am I?
❏ Frontend architect at ilegra
❏ Graduated in Analysis and System
Development at FATEC Senai
❏ Started in 2012 on IT world
❏ Experience with Arch Front (Angular,
React, React Native, Vue, NodeJS, Micro-
fronts, SSR, BFF, GraphQL, PWA and
others)
@adrianlemess
Summary
❏ JavaScript introduction
❏ Objects
❏ Functions
❏ DOM and QuerySelector
❏ Events
Setup
❏ Setup de ambiente
❏ VSCode
❏ Extensões (git blame, git history, eslint, HTML snippets, JavaScript (ES6)
code snippets)
❏ Chrome - DevTools
Introduction
History
1995
JavaScript
creation at
Netscape
by Brendan
Eich
1996
Microsoft
releases
JScript for
IE 3
1997
JavaScript
was
standardized
in EcmaScript
spec
2005
Ajax released
and the web
2.0 age
started
2006
JQuery 1.0
was released
2009
Chrome and
V8 engine
launched
2010
NodeJS was
released
2015
EcmaScript 6
was released
Current
3 JavaScript
framework is
launched by
minute
What is
JavaScript/EcmaScript?
❏ Browser Interpreted Language
❏ Born to make websites dynamic
❏ Browser-integrated language
❏ Object Based (Window, Date (), Matrix (), Mathematics ())
❏ Event Oriented Language
EcmaScript Specs
❏ ECMAScript 1 (1997)
❏ First version, released in 10 days
❏ ECMAScript 2 (1998)
❏ W3C - DOM lvl 1 and 2
❏ Alignment with ISO/IEC 16262 and became a international standard
❏ ECMAScript 3 (1999)
❏ Implementation with do-while, regular expressions, exceptions, among
other things
❏ ECMAScript 4 (abandoned in July 2008)
EcmaScript Specs
❏ ECMAScript 5 (2009)
❏ Several improvements over version 3: support to JSON, getters and setters,
'use strict', among others
❏ ECMAScript 6 (2015)
❏ Template string, let e const, arrow function and a lot of improvements
❏ ES7, ES8, ES Next - the lasts upgrades with others
improvements like async-await
What we can achieve?
❏ Animations
❏ Handle HTML Elements
❏ Add or remove HTML elements
❏ Change styles
❏ Access Values
❏ Handle XML and JSON Files
❏ Server side: with NodeJS (I.E. SSR, Backend for Frontend,
GraphQL)
❏ Mobile with hybrid frameworks - React Native, Ionic, phonegap,
nativescript, among others
Data type
Basic types
❏ number
❏ boolean
❏ string
❏ object
❏ function
Object Types
❏ Object
❏ Date
❏ Array
Types with no
value
❏ null
❏ undefined
Falsy Values
❏ false === false
❏ 0 === false
❏ “” (empty string) === false
❏ null === false
❏ undefined === false
❏ NaN (Not A Number) === false
How to use
❏ We can insert JavaScript code in the following ways:
❏ Inside the body of the <body> ... </body> page
❏ Inside the page header <head> ... </head>
❏ Inside an html tag
❏ In a separate html file saved with the extension .js
❏ In the browser console (for testing purpose) (f12 or inspect)
<body> or <head>
<html>
<head>
<script>
alert('script tag in head');
</script>
</head>
<body>
<!-- Page -->
</body>
</html>
<html>
<head>
<!-- Meta tags -->
</head>
<body>
<script>
alert('script tag in body');
</script>
</body>
</html>
Code in tag inline
<html>
<head>
<!-- Meta tags -->
</head>
<body>
<button onclick="alert('on click button'); ">
Alert
</button>
</body>
</html>
File
// file.js
function foo() {
console.log('bar');
}
Console
Basic Concepts
❏ JavaScript is case sensitive (var animalName is different from var AnimalName
❏ Dynamic typing - Types Are Associated With Values, Not As Variables -> Poorly
Typed Variables
❏ var name = "adrian";
❏ var numInt = 10;
❏ var numFloat = 5.5;
❏ Comments
❏ / * block * /
❏ // Line
❏ Semicolon (;) at the end of each line is optional, but is a good practice.
Arithmetic Operators
❏ var x = 10
Assignment Operators
❏ var x = 10
❏ var y = 2
Comparison Operators
❏ var x = 10
Objects
Objects
// Objects is map in pairs (key, value)
var obj = {
foo: 1,
bar: 2
};
// The keys will always be coverted to string
var obj = {
// this key will be "1" and not 1.
// Keys non-string will be converted to string
1: 15,
2: -50
};
// Quotes are optional
var obj = {
"1": 15,
"2": -50
};
// Values can be of any type.
var obj = {
foo: 1000,
bar: 'Adrian',
baz: function() {},
zot: [1, 2, 3],
foobar: /^a/
};
Object properties
var obj = {
x: 1,
y: 2
};
// dot notation
obj.x; //1
// ... or Array notation
obj["x"]; //1
// array notations are useful with
// expressions or compound names
var key = 'x';
obj[key]; //1
// or
obj["pet-name"] = "snow"
Acessing multiple
properties in an Object
var obj = {
x: 1,
y: 2
};
// Using for in
for (var key in obj) {
obj[key];
}
// Using interator - functional programming approach
object.keys(obj).forEach(function(key) {
obj[key];
});
Objects are dynamic
var obj = {
x: 1,
y: 2
};
"x" in obj; //true
"z" in obj; //false
// Keys can be dynamically add
obj.z = 23;
"z" in obj; //true
//... or removed
delete obj.z;
"z" in obj; //false
// Common mistake: This not delete an key
obj.x = undefined;
"x" in obj; //true
// Just assign a undefined value for the key
obj.x === undefined; //true
// To delete a key
delete obj.x;
"x" in obj;
Keys with Expression
// You cannot assign a variable directly in a key:
var key = "x" + "y"
// this wont work as expected
var obj = {
key : 3 // the key will be "key" and not "xy"
};
// ... this way is not valid neither:
var obj = {
"x" + "y": 3 // expressions are not allowed here
};
// but this way you can
var obj = {};
obj["x" + "y"] = 3;
// Pay attention
var obj = {};
var arr = [1, 2];
obj[arr] = 4;
"1,2" in obj; //true
var obj2 = { name: 'adrian' };
obj[obj2] = 3;
"[object Object]" in obj; //true
// keys are converted by string
// avoiding [ object Object ]
obj[JSON.stringify(obj2)]
'{"name":"adrian"}' in obj; //true
Arrays
// Arrays are a different kind of object
typeof [] === 'object'; //true
// Arrays may have "holes"
var arr = [1,,,2];
// indexes are keys
"0" in arr; //true
// holes are not valid keys
"1" in arr; //false
// The holes values is undefined
arr[1] === undefined; //true
// But beware, it's not the same thing to
// be undefined and has the undefined value
arr[1] = undefined; // This is not a hole anymore
arr[1] === undefined; // true
"1" in arr; // true <- Here is the difference
// Arrays are dynamically
var arr = [1, 2, 3];
arr[500] = 4; // from index 3 to 499 will be holes
// The array size is not what suppost to be
arr.length; //501
Arrays
// Don't use for in to iterate arrays
// because the interaction order cannot be guaranteed
// There are multiple method to iterate arrays
// forEach, map, reduce, filter, some, every, ...
// Useful tip: Don't use "delete" to remove values in array,
// it creates holes
var arr = [1, 2, 3];
delete arr[3];
arr.length; //3
// to correctly remove use the splice method
// arr.splice(startIndex, quantity);
arr.splice(2, 1);
arr.length; //2
Functions
Sintaxe
function foo() {
return 'bar';
}
High Order Functions
❏ In Javascript, functions are values:
❏ Assigned as an identifier (variable) value
❏ Assigned to object property values
❏ Passed as arguments
❏ Returned from functions
❏ Higher-order functions are functions that take other functions
as arguments or return functions as their results.
Functions inside a variable
// Functions can be executed inside the scope where it was
// declared. (Window, object, function)
function helloWorld() {
return 'Hello World'
}
// We might pass a declarative function inside a variable
var showHelloWorld = function helloWorld(name) {
return 'Hello ' + name;
}
showHelloWorld();
// But we also might pass an anonymus function inside a variable
var showHelloWorld = function(name) {
return 'Hello ' + name;
}
showHelloWorld();
Returning functions
// In JavaScript a function might return another function!
function isBiggerThan(n) {
return function number(m) {
return m > n;
}
}
// And we may pass to a variable
var isBiggerThan10 = isBiggerThan(10);
isBiggerThan10(5) // return false
isBiggerThan10(11) // return true
isBiggerThan10(10) // return false
Functions as param
// In JavaScript we can receive a function as param
function calculate(fn, numA, numB) {
return fn(numA, numB);
}
const sum = function (x, y) {
return x + y;
};
const mult = function (x, y) {
return x * y;
};
calculate(sum, 2, 5); // 7
calculate(mult, 2, 5); // 10
...Arguments
// Every function in JavaScript has a default param called Arguments
function findMax() {
var i;
var max = -Infinity;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
var x = findMax(1, 123, 500, 115, 44, 88);
DOM and QuerySelector
DOM - What is?
❏ Document Object Model
❏ It's a spec to manipulate HTML and XML documents
❏ Add new elements
❏ Remove elements
❏ Update elements
❏ Accessing elements
❏ Interoperability - any language can implement the API DOM
❏ After the browser reads your HTML document, it creates a
representational tree called the Document Object Model and
defines how that tree can be accessed
Representation By Browser
Representation by the
browser
❏ Node - Each part of the tree is know as Node.
❏ Each node has a representation name (<p>, <h1>, <body>)
❏ The elements is not always unique, that's why it's possible to identify by an ID
attribute
❏ Document: Its the first Node, It treats all the HTML documents.
❏ The nodes might be:
❏ Elements: All the tags that are inside your HTML or XML turn into a DOM
element.
❏ Text: All the tags’ content.
❏ Attributes: All the attributes from a specific HTML element. In the image, the
attribute class=”hero” is an attribute from the <p> element.
Table Tree Representation
Acessing the DOM: HTML Example
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>DOM (Document Object Model)</title>
</head>
<body>
<div class="container">
<h1><time>00:00:00</time></h1>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
</div>
</body>
</html>
Document Methods
❏ It's the connection between our code and the Nodes and Events from DOM
❏ The mosts important methods are:
❏ document.getElementById('start') - returns the node element with a specific
ID or null if the ID don't exist
❏ document.getElementsByClassName('container') - return a HTMLCollection
with all the elements with the specified class or null if the class don't exist
❏ document.getElementsByTagName('body') - return a HTMLCollection with
all the tag elements specified or null if the tag is not in use
Document Methods:
QuerySelector
❏ It returns the first element that has the specific CSS selector passed
❏ Just remember that the selector should follow the CSS syntax
❏ ID: #start
❏ Tag: body
❏ class: .container
❏ Returns null in case you do not have any selector matched
ex: var resetButton = document.querySelector('#reset');
Document Methods:
QuerySelectorAll
❏ Very similar with QuerySelector() but the output is a all the elements matched
with the selector and only the first
❏ Returns null in case you do not have any selector matched
ex: var myButtons = document.querySelector('#buttons');
More about selectors:
https://flukeout.github.io/
DOM properties
❏ There a methods to return elements, text, comments and so on
❏ .childNodes - return a node list with child elements
❏ .firstChild - return a first child of an element
var container = document.querySelector('.container');
var getContainerChilds = container.childNodes;
var container = document.querySelector('.container');
var getFirstChild = container.firstChild;
DOM properties
❏ .nodeName - return the node name
❏ .nodeValue - return a node value
var container = document.querySelector('.container');
var getName = container.nodeName;
var container = document.querySelector('.container')
var getValue = container.nodeValue;
DOM properties Elements
❏ Those properties return HTML Elements
❏ .parentNode - This property returns the parent of the node
given.
❏ .firstElementChild - Returns the first child element of the given
element.
var container = document.querySelector('.container')
var getParent = container.parentNode;
var container = document.querySelector('.container')
var getValue = container.firstElementChild;
DOM properties Elements
❏ .lastElementChild - Returns the last child element of the given
element.
var container = document.querySelector('.container')
var getValue = container.lastElementChild;
JavaScript Events
Categories
❏ W3 DOM Specification: W3C manages all the DOM event specifications, except
those that deal with form elements.
❏ HTML5 Specification: These include all the events specifically used with HTML.
These include submit, input, etc. New additions to this category include
hashchange, beforeunload, etc.
❏ Browser Object Models: W3 specifications don’t yet cover these events. They deal
with touchscreen devices and the events in this section include touchstart,
touchend, etc.
Events types
❏ User interface events - events from browser. The event listener is on window
object
❏ load, unload, error, resize and scroll
❏ HTML events - this events fire on HTML elements gain or lose focus.
❏ focus, blur
❏ Mouse events - events when the mouse move or click
❏ click (and touch screen), dblclick, mousedown, mouseup, mouseover,
mouseout, mousemove
❏ Keyboard events - events fired with a user interaction on a keyboard. Each key
has a unique code
❏ keydown, keypress, keyup
Events types
❏ Form Events
❏ submit, change, input
❏ Mutation events and observers - mutation events listening the DOM and
mutation observers has the same event but it’s fired in batches - more
performance
❏ DOMNodeInserted, DOMNodeRemoved, DOMSubtreeModified
❏ HTML 5 Events - Modern page level events like gesture and movements and
better support like phones and tablets
❏ DOMContentLoaded, hashchange, beforeunload
❏ CSS Events - These events trigger when the script encounters a CSS element
❏ transitionend, animationstart, animationiteration, animationend
Events References
❏ https://developer.mozilla.org/pt-BR/docs/Web/Events
How to use
❏ Click Button:
var startButton = document.querySelector('#start');
startButton.addEventListener('click', function(event) {
// Do something here.
}, false);
How to use
❏ Mouse up on Button:
var startButton = document.querySelector('#start');
startButton.addEventListener('mouseup', function(event) {
alert('Mouse UP')
}, false);
Credits
❏ https://www.freecodecamp.org/news/whats-the-document-
object-model-and-why-you-should-know-how-to-use-it-
1a2d0bc5429d/
❏ https://dev.to/damcosset/higher-order-functions-in-javascript-
4j8b
❏ https://developer.mozilla.org

More Related Content

What's hot (20)

eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java Developers
Bob McCune
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
go_oh
 
Java script
Java scriptJava script
Java script
vishal choudhary
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
Bedis ElAchèche
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
shreesenthil
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
Enrique Juan de Dios
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
msemenistyi
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )
Victor Verhaagen
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
Mohammed Sazid Al Rashid
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
Doeun KOCH
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web Developers
Joris Verbogt
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java Developers
Bob McCune
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
go_oh
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
msemenistyi
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )
Victor Verhaagen
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
Doeun KOCH
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web Developers
Joris Verbogt
 

Similar to Java script (20)

lecture 6 javascript event and event handling.ppt
lecture 6 javascript event and event handling.pptlecture 6 javascript event and event handling.ppt
lecture 6 javascript event and event handling.ppt
ULADATZ
 
Javascript.ppt
Javascript.pptJavascript.ppt
Javascript.ppt
NoralieNicol
 
JavaScript Needn't Hurt!
JavaScript Needn't Hurt!JavaScript Needn't Hurt!
JavaScript Needn't Hurt!
Thomas Kjeldahl Nilsson
 
Cordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced JavascriptCordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced Javascript
Binu Paul
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
AAFREEN SHAIKH
 
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
sharvaridhokte
 
JavaScripts & jQuery
JavaScripts & jQueryJavaScripts & jQuery
JavaScripts & jQuery
Asanka Indrajith
 
jQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsjQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation Labs
Prasad Shende
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
Denis Ristic
 
Javascript
JavascriptJavascript
Javascript
Manav Prasad
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications
surajshreyans
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
Laurence Svekis ✔
 
Javascript
JavascriptJavascript
Javascript
Prashant Kumar
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
Núcleo de Electrónica e Informática da Universidade do Algarve
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to Programming
Cindy Royal
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
Web Zhao
 
Learn java script
Learn java scriptLearn java script
Learn java script
Mahmoud Asadi
 
Javascript
JavascriptJavascript
Javascript
Adil Jafri
 
lecture 6 javascript event and event handling.ppt
lecture 6 javascript event and event handling.pptlecture 6 javascript event and event handling.ppt
lecture 6 javascript event and event handling.ppt
ULADATZ
 
Cordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced JavascriptCordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced Javascript
Binu Paul
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
AAFREEN SHAIKH
 
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
sharvaridhokte
 
jQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsjQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation Labs
Prasad Shende
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
Denis Ristic
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications
surajshreyans
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to Programming
Cindy Royal
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
Web Zhao
 
Ad

More from Adrian Caetano (9)

Typescript
TypescriptTypescript
Typescript
Adrian Caetano
 
Web assembly
Web assemblyWeb assembly
Web assembly
Adrian Caetano
 
Electron
ElectronElectron
Electron
Adrian Caetano
 
Protobuff
ProtobuffProtobuff
Protobuff
Adrian Caetano
 
Workers
WorkersWorkers
Workers
Adrian Caetano
 
Frontend training
Frontend trainingFrontend training
Frontend training
Adrian Caetano
 
Puppeteer
PuppeteerPuppeteer
Puppeteer
Adrian Caetano
 
Bff and GraphQL
Bff and GraphQLBff and GraphQL
Bff and GraphQL
Adrian Caetano
 
Treinamento frontend
Treinamento frontendTreinamento frontend
Treinamento frontend
Adrian Caetano
 
Ad

Recently uploaded (20)

Shortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome ThemShortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome Them
TECH EHS Solution
 
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
Nacho Cougil
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
Optimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing SystemsOptimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing Systems
Insurance Tech Services
 
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
Philip Schwarz
 
Issues in AI Presentation and machine learning.pptx
Issues in AI Presentation and machine learning.pptxIssues in AI Presentation and machine learning.pptx
Issues in AI Presentation and machine learning.pptx
Jalalkhan657136
 
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATIONAI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
miso_uam
 
Software Risk and Quality management.pptx
Software Risk and Quality management.pptxSoftware Risk and Quality management.pptx
Software Risk and Quality management.pptx
HassanBangash9
 
ICDL FULL STANDARD 2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
ICDL FULL STANDARD  2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdfICDL FULL STANDARD  2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
ICDL FULL STANDARD 2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
M. Luisetto Pharm.D.Spec. Pharmacology
 
Oliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdfOliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdf
GiliardGodoi1
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
Risk Management in Software Projects: Identifying, Analyzing, and Controlling...
Risk Management in Software Projects: Identifying, Analyzing, and Controlling...Risk Management in Software Projects: Identifying, Analyzing, and Controlling...
Risk Management in Software Projects: Identifying, Analyzing, and Controlling...
gauravvmanchandaa200
 
Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...
Rishab Acharya
 
Custom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdfCustom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdf
Digital Aptech
 
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire
 
Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
officeiqai
 
Techdebt handling with cleancode focus and as risk taker
Techdebt handling with cleancode focus and as risk takerTechdebt handling with cleancode focus and as risk taker
Techdebt handling with cleancode focus and as risk taker
RajaNagendraKumar
 
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfHow to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
QuickBooks Training
 
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjaraswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
muhammadalikhanalikh1
 
Shortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome ThemShortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome Them
TECH EHS Solution
 
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
How John started to like TDD (instead of hating it) (ViennaJUG, June'25)
Nacho Cougil
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
Optimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing SystemsOptimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing Systems
Insurance Tech Services
 
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
Philip Schwarz
 
Issues in AI Presentation and machine learning.pptx
Issues in AI Presentation and machine learning.pptxIssues in AI Presentation and machine learning.pptx
Issues in AI Presentation and machine learning.pptx
Jalalkhan657136
 
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATIONAI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION
miso_uam
 
Software Risk and Quality management.pptx
Software Risk and Quality management.pptxSoftware Risk and Quality management.pptx
Software Risk and Quality management.pptx
HassanBangash9
 
ICDL FULL STANDARD 2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
ICDL FULL STANDARD  2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdfICDL FULL STANDARD  2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
ICDL FULL STANDARD 2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
M. Luisetto Pharm.D.Spec. Pharmacology
 
Oliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdfOliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdf
GiliardGodoi1
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
Risk Management in Software Projects: Identifying, Analyzing, and Controlling...
Risk Management in Software Projects: Identifying, Analyzing, and Controlling...Risk Management in Software Projects: Identifying, Analyzing, and Controlling...
Risk Management in Software Projects: Identifying, Analyzing, and Controlling...
gauravvmanchandaa200
 
Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...
Rishab Acharya
 
Custom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdfCustom Software Development: Types, Applications and Benefits.pdf
Custom Software Development: Types, Applications and Benefits.pdf
Digital Aptech
 
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire
 
Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
Feeling Lost in the Blue? Exploring a New Path: AI Mental Health Counselling ...
officeiqai
 
Techdebt handling with cleancode focus and as risk taker
Techdebt handling with cleancode focus and as risk takerTechdebt handling with cleancode focus and as risk taker
Techdebt handling with cleancode focus and as risk taker
RajaNagendraKumar
 
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfHow to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
QuickBooks Training
 
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjaraswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
muhammadalikhanalikh1
 

Java script

  • 2. Who am I? ❏ Frontend architect at ilegra ❏ Graduated in Analysis and System Development at FATEC Senai ❏ Started in 2012 on IT world ❏ Experience with Arch Front (Angular, React, React Native, Vue, NodeJS, Micro- fronts, SSR, BFF, GraphQL, PWA and others) @adrianlemess
  • 3. Summary ❏ JavaScript introduction ❏ Objects ❏ Functions ❏ DOM and QuerySelector ❏ Events
  • 4. Setup ❏ Setup de ambiente ❏ VSCode ❏ Extensões (git blame, git history, eslint, HTML snippets, JavaScript (ES6) code snippets) ❏ Chrome - DevTools
  • 6. History 1995 JavaScript creation at Netscape by Brendan Eich 1996 Microsoft releases JScript for IE 3 1997 JavaScript was standardized in EcmaScript spec 2005 Ajax released and the web 2.0 age started 2006 JQuery 1.0 was released 2009 Chrome and V8 engine launched 2010 NodeJS was released 2015 EcmaScript 6 was released Current 3 JavaScript framework is launched by minute
  • 7. What is JavaScript/EcmaScript? ❏ Browser Interpreted Language ❏ Born to make websites dynamic ❏ Browser-integrated language ❏ Object Based (Window, Date (), Matrix (), Mathematics ()) ❏ Event Oriented Language
  • 8. EcmaScript Specs ❏ ECMAScript 1 (1997) ❏ First version, released in 10 days ❏ ECMAScript 2 (1998) ❏ W3C - DOM lvl 1 and 2 ❏ Alignment with ISO/IEC 16262 and became a international standard ❏ ECMAScript 3 (1999) ❏ Implementation with do-while, regular expressions, exceptions, among other things ❏ ECMAScript 4 (abandoned in July 2008)
  • 9. EcmaScript Specs ❏ ECMAScript 5 (2009) ❏ Several improvements over version 3: support to JSON, getters and setters, 'use strict', among others ❏ ECMAScript 6 (2015) ❏ Template string, let e const, arrow function and a lot of improvements ❏ ES7, ES8, ES Next - the lasts upgrades with others improvements like async-await
  • 10. What we can achieve? ❏ Animations ❏ Handle HTML Elements ❏ Add or remove HTML elements ❏ Change styles ❏ Access Values ❏ Handle XML and JSON Files ❏ Server side: with NodeJS (I.E. SSR, Backend for Frontend, GraphQL) ❏ Mobile with hybrid frameworks - React Native, Ionic, phonegap, nativescript, among others
  • 11. Data type Basic types ❏ number ❏ boolean ❏ string ❏ object ❏ function Object Types ❏ Object ❏ Date ❏ Array Types with no value ❏ null ❏ undefined
  • 12. Falsy Values ❏ false === false ❏ 0 === false ❏ “” (empty string) === false ❏ null === false ❏ undefined === false ❏ NaN (Not A Number) === false
  • 13. How to use ❏ We can insert JavaScript code in the following ways: ❏ Inside the body of the <body> ... </body> page ❏ Inside the page header <head> ... </head> ❏ Inside an html tag ❏ In a separate html file saved with the extension .js ❏ In the browser console (for testing purpose) (f12 or inspect)
  • 14. <body> or <head> <html> <head> <script> alert('script tag in head'); </script> </head> <body> <!-- Page --> </body> </html> <html> <head> <!-- Meta tags --> </head> <body> <script> alert('script tag in body'); </script> </body> </html>
  • 15. Code in tag inline <html> <head> <!-- Meta tags --> </head> <body> <button onclick="alert('on click button'); "> Alert </button> </body> </html>
  • 16. File // file.js function foo() { console.log('bar'); }
  • 18. Basic Concepts ❏ JavaScript is case sensitive (var animalName is different from var AnimalName ❏ Dynamic typing - Types Are Associated With Values, Not As Variables -> Poorly Typed Variables ❏ var name = "adrian"; ❏ var numInt = 10; ❏ var numFloat = 5.5; ❏ Comments ❏ / * block * / ❏ // Line ❏ Semicolon (;) at the end of each line is optional, but is a good practice.
  • 20. Assignment Operators ❏ var x = 10 ❏ var y = 2
  • 23. Objects // Objects is map in pairs (key, value) var obj = { foo: 1, bar: 2 }; // The keys will always be coverted to string var obj = { // this key will be "1" and not 1. // Keys non-string will be converted to string 1: 15, 2: -50 }; // Quotes are optional var obj = { "1": 15, "2": -50 }; // Values can be of any type. var obj = { foo: 1000, bar: 'Adrian', baz: function() {}, zot: [1, 2, 3], foobar: /^a/ };
  • 24. Object properties var obj = { x: 1, y: 2 }; // dot notation obj.x; //1 // ... or Array notation obj["x"]; //1 // array notations are useful with // expressions or compound names var key = 'x'; obj[key]; //1 // or obj["pet-name"] = "snow"
  • 25. Acessing multiple properties in an Object var obj = { x: 1, y: 2 }; // Using for in for (var key in obj) { obj[key]; } // Using interator - functional programming approach object.keys(obj).forEach(function(key) { obj[key]; });
  • 26. Objects are dynamic var obj = { x: 1, y: 2 }; "x" in obj; //true "z" in obj; //false // Keys can be dynamically add obj.z = 23; "z" in obj; //true //... or removed delete obj.z; "z" in obj; //false // Common mistake: This not delete an key obj.x = undefined; "x" in obj; //true // Just assign a undefined value for the key obj.x === undefined; //true // To delete a key delete obj.x; "x" in obj;
  • 27. Keys with Expression // You cannot assign a variable directly in a key: var key = "x" + "y" // this wont work as expected var obj = { key : 3 // the key will be "key" and not "xy" }; // ... this way is not valid neither: var obj = { "x" + "y": 3 // expressions are not allowed here }; // but this way you can var obj = {}; obj["x" + "y"] = 3; // Pay attention var obj = {}; var arr = [1, 2]; obj[arr] = 4; "1,2" in obj; //true var obj2 = { name: 'adrian' }; obj[obj2] = 3; "[object Object]" in obj; //true // keys are converted by string // avoiding [ object Object ] obj[JSON.stringify(obj2)] '{"name":"adrian"}' in obj; //true
  • 28. Arrays // Arrays are a different kind of object typeof [] === 'object'; //true // Arrays may have "holes" var arr = [1,,,2]; // indexes are keys "0" in arr; //true // holes are not valid keys "1" in arr; //false // The holes values is undefined arr[1] === undefined; //true // But beware, it's not the same thing to // be undefined and has the undefined value arr[1] = undefined; // This is not a hole anymore arr[1] === undefined; // true "1" in arr; // true <- Here is the difference // Arrays are dynamically var arr = [1, 2, 3]; arr[500] = 4; // from index 3 to 499 will be holes // The array size is not what suppost to be arr.length; //501
  • 29. Arrays // Don't use for in to iterate arrays // because the interaction order cannot be guaranteed // There are multiple method to iterate arrays // forEach, map, reduce, filter, some, every, ... // Useful tip: Don't use "delete" to remove values in array, // it creates holes var arr = [1, 2, 3]; delete arr[3]; arr.length; //3 // to correctly remove use the splice method // arr.splice(startIndex, quantity); arr.splice(2, 1); arr.length; //2
  • 32. High Order Functions ❏ In Javascript, functions are values: ❏ Assigned as an identifier (variable) value ❏ Assigned to object property values ❏ Passed as arguments ❏ Returned from functions ❏ Higher-order functions are functions that take other functions as arguments or return functions as their results.
  • 33. Functions inside a variable // Functions can be executed inside the scope where it was // declared. (Window, object, function) function helloWorld() { return 'Hello World' } // We might pass a declarative function inside a variable var showHelloWorld = function helloWorld(name) { return 'Hello ' + name; } showHelloWorld(); // But we also might pass an anonymus function inside a variable var showHelloWorld = function(name) { return 'Hello ' + name; } showHelloWorld();
  • 34. Returning functions // In JavaScript a function might return another function! function isBiggerThan(n) { return function number(m) { return m > n; } } // And we may pass to a variable var isBiggerThan10 = isBiggerThan(10); isBiggerThan10(5) // return false isBiggerThan10(11) // return true isBiggerThan10(10) // return false
  • 35. Functions as param // In JavaScript we can receive a function as param function calculate(fn, numA, numB) { return fn(numA, numB); } const sum = function (x, y) { return x + y; }; const mult = function (x, y) { return x * y; }; calculate(sum, 2, 5); // 7 calculate(mult, 2, 5); // 10
  • 36. ...Arguments // Every function in JavaScript has a default param called Arguments function findMax() { var i; var max = -Infinity; for (i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max; } var x = findMax(1, 123, 500, 115, 44, 88);
  • 38. DOM - What is? ❏ Document Object Model ❏ It's a spec to manipulate HTML and XML documents ❏ Add new elements ❏ Remove elements ❏ Update elements ❏ Accessing elements ❏ Interoperability - any language can implement the API DOM ❏ After the browser reads your HTML document, it creates a representational tree called the Document Object Model and defines how that tree can be accessed
  • 40. Representation by the browser ❏ Node - Each part of the tree is know as Node. ❏ Each node has a representation name (<p>, <h1>, <body>) ❏ The elements is not always unique, that's why it's possible to identify by an ID attribute ❏ Document: Its the first Node, It treats all the HTML documents. ❏ The nodes might be: ❏ Elements: All the tags that are inside your HTML or XML turn into a DOM element. ❏ Text: All the tags’ content. ❏ Attributes: All the attributes from a specific HTML element. In the image, the attribute class=”hero” is an attribute from the <p> element.
  • 42. Acessing the DOM: HTML Example <!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>DOM (Document Object Model)</title> </head> <body> <div class="container"> <h1><time>00:00:00</time></h1> <button id="start">Start</button> <button id="stop">Stop</button> <button id="reset">Reset</button> </div> </body> </html>
  • 43. Document Methods ❏ It's the connection between our code and the Nodes and Events from DOM ❏ The mosts important methods are: ❏ document.getElementById('start') - returns the node element with a specific ID or null if the ID don't exist ❏ document.getElementsByClassName('container') - return a HTMLCollection with all the elements with the specified class or null if the class don't exist ❏ document.getElementsByTagName('body') - return a HTMLCollection with all the tag elements specified or null if the tag is not in use
  • 44. Document Methods: QuerySelector ❏ It returns the first element that has the specific CSS selector passed ❏ Just remember that the selector should follow the CSS syntax ❏ ID: #start ❏ Tag: body ❏ class: .container ❏ Returns null in case you do not have any selector matched ex: var resetButton = document.querySelector('#reset');
  • 45. Document Methods: QuerySelectorAll ❏ Very similar with QuerySelector() but the output is a all the elements matched with the selector and only the first ❏ Returns null in case you do not have any selector matched ex: var myButtons = document.querySelector('#buttons');
  • 47. DOM properties ❏ There a methods to return elements, text, comments and so on ❏ .childNodes - return a node list with child elements ❏ .firstChild - return a first child of an element var container = document.querySelector('.container'); var getContainerChilds = container.childNodes; var container = document.querySelector('.container'); var getFirstChild = container.firstChild;
  • 48. DOM properties ❏ .nodeName - return the node name ❏ .nodeValue - return a node value var container = document.querySelector('.container'); var getName = container.nodeName; var container = document.querySelector('.container') var getValue = container.nodeValue;
  • 49. DOM properties Elements ❏ Those properties return HTML Elements ❏ .parentNode - This property returns the parent of the node given. ❏ .firstElementChild - Returns the first child element of the given element. var container = document.querySelector('.container') var getParent = container.parentNode; var container = document.querySelector('.container') var getValue = container.firstElementChild;
  • 50. DOM properties Elements ❏ .lastElementChild - Returns the last child element of the given element. var container = document.querySelector('.container') var getValue = container.lastElementChild;
  • 52. Categories ❏ W3 DOM Specification: W3C manages all the DOM event specifications, except those that deal with form elements. ❏ HTML5 Specification: These include all the events specifically used with HTML. These include submit, input, etc. New additions to this category include hashchange, beforeunload, etc. ❏ Browser Object Models: W3 specifications don’t yet cover these events. They deal with touchscreen devices and the events in this section include touchstart, touchend, etc.
  • 53. Events types ❏ User interface events - events from browser. The event listener is on window object ❏ load, unload, error, resize and scroll ❏ HTML events - this events fire on HTML elements gain or lose focus. ❏ focus, blur ❏ Mouse events - events when the mouse move or click ❏ click (and touch screen), dblclick, mousedown, mouseup, mouseover, mouseout, mousemove ❏ Keyboard events - events fired with a user interaction on a keyboard. Each key has a unique code ❏ keydown, keypress, keyup
  • 54. Events types ❏ Form Events ❏ submit, change, input ❏ Mutation events and observers - mutation events listening the DOM and mutation observers has the same event but it’s fired in batches - more performance ❏ DOMNodeInserted, DOMNodeRemoved, DOMSubtreeModified ❏ HTML 5 Events - Modern page level events like gesture and movements and better support like phones and tablets ❏ DOMContentLoaded, hashchange, beforeunload ❏ CSS Events - These events trigger when the script encounters a CSS element ❏ transitionend, animationstart, animationiteration, animationend
  • 56. How to use ❏ Click Button: var startButton = document.querySelector('#start'); startButton.addEventListener('click', function(event) { // Do something here. }, false);
  • 57. How to use ❏ Mouse up on Button: var startButton = document.querySelector('#start'); startButton.addEventListener('mouseup', function(event) { alert('Mouse UP') }, false);

Editor's Notes

  • #4: Falar que o foco vai ser ES5 pra depois vermos as diferenças do que entrou no ES6 em diante
  • #5: Começar abrindo o devtools e mostrando todo ele
  • #7: Falar que foi feito em 10 dias
  • #12: NULL must be assigned and has no value and undefined means the variable is not defined
  • #23: Falar que vai apresentar códigos e que eles podem executar esses blocos de código no console pra terem um melhor aprendizado
  • #27: Falar que deletar um atributo de um objeto é um erro comum que a galera faz
  • #28: Falar que deletar um atributo de um objeto é um erro comum que a galera faz
  • #29: Falar que deletar um atributo de um objeto é um erro comum que a galera faz
  • #30: Falar que deletar um atributo de um objeto é um erro comum que a galera faz
  • #32: Falar que deletar um atributo de um objeto é um erro comum que a galera faz
  • #33: High order func
  • #34: Falar que deletar um atributo de um objeto é um erro comum que a galera faz
  • #35: Falar que deletar um atributo de um objeto é um erro comum que a galera faz
  • #36: Falar que deletar um atributo de um objeto é um erro comum que a galera faz
  • #37: Falar que deletar um atributo de um objeto é um erro comum que a galera faz
  • #38: Falar que vai apresentar códigos e que eles podem executar esses blocos de código no console pra terem um melhor aprendizado
  • #39: High order func
  • #40: High order func
  • #42: High order func
  • #43: Pedir pra salvarem num index.html, abrir pelo chrome e testarem os métodos
  • #52: Falar que vai apresentar códigos e que eles podem executar esses blocos de código no console pra terem um melhor aprendizado
  • #54: MouoseDown - Varia: Inicia um operação de arrastar/soltar; inicia a seleção de texto; inicia a interação de rolagem/arrastar (junto do botão do meio do mouse, se suportado) MouseUp - Ocorre quando solva o dedo do clique mouseover - quando o cursor fica encima de um elemento mouseout - quando o cursos sai do foco de um elemento mousemove - quando o cursor passa encima de qualquer posição do elemento keydown e keypress são parecidos, mas o keypress não emiti pra algumas teclas como enter, tab e outras. Ambos se tu pressiona repete uma tecla repetidamente keyup - quando o usuário solta a tecla
  • #55: Changes - when various inputs change input - quando um input troca o valor hashChange - when URL change specif parts beforeUnload - happening when the user will exit the page. Its good to show a dialog and confirm a data not saved yet transitioned - ocorre quando uma transição de CSS acaba animationstart - These events fire when CSS animation starts in the program. animationinteraction - ocorre quando uma animação se repete, com esse evento consegue pegar a quantidade de mudanças que ocorre animationend - quando a animação termina
  • #56: Changes - when various inputs change input - quando um input troca o valor hashChange - when URL change specif parts beforeUnload - happening when the user will exit the page. Its good to show a dialog and confirm a data not saved yet transitioned - ocorre quando uma transição de CSS acaba animationstart - These events fire when CSS animation starts in the program. animationinteraction - ocorre quando uma animação se repete, com esse evento consegue pegar a quantidade de mudanças que ocorre animationend - quando a animação termina
  • #57: Se true, useCapture indica que o usuário deseja iniciar uma captura. Depois de iniciada a captura, todos os eventos do tipo especificado serão enviados à listener registrada antes de serem enviados à qualquer EventTarget abaixo dela na hierarquia de DOMs.
  • #58: Se true, useCapture indica que o usuário deseja iniciar uma captura. Depois de iniciada a captura, todos os eventos do tipo especificado serão enviados à listener registrada antes de serem enviados à qualquer EventTarget abaixo dela na hierarquia de DOMs.