Dom Promises Modules
Dom Promises Modules
document.querySelector('p');
You can also use other CSS selectors such as an element’s . class or
its # ID.
document.getElementById('bio').innerHTML = 'The
description';
The example chains so that it selects the element with an ID of ‘bio’
and sets its .innerHTML to the text 'The description'.
Style an element
For example, the following code selects the first element with
a class of blue and assigns blue as the background-color:
document.querySelector('.blue').style.fontFamily
= 'Roboto';
Defer attribute
The defer attribute specifies scripts should be executed after
the HTML file is completely parsed. When the HTML parser
encounters a <script> element with the defer attribute, it loads the
script but defers the actual execution of the JavaScript until after it
finishes parsing the rest of the elements in the HTML file.
Async attribute
The async attribute loads and executes the script
asynchronously with the rest of the webpage. This means that,
similar to the defer attribute, the HTML parser will continue parsing
the rest of the HTML as the script is downloaded in the background.
However, with the async attribute, the script will not wait until the
entire page is parsed: it will execute immediately after it has been
downloaded. Here is an example of the async tag:
getElementsByClassName getElementsByTagName
The .getElementsByClassName() and .getElementsByTagName() m
ethods which return an array of elements, instead of just one
element. You can use bracket notation to access individual elements
of an array:
Create Elements
However, it does not append it to the document. It creates an empty
element with no inner HTML.
paragraph.id = 'info';
paragraph.innerHTML = 'The text inside the paragraph';
Above, we use the .id property to assign 'info' as ID and
the .innerHTML property to set 'The text inside the
paragraph' as the content of the <p> element.
Insert Elements
The following code appends the <p> element stored in
the paragraph variable to the document body.
document.body.appendChild(paragraph);
Remove an Element
let paragraph = document.querySelector('p');
document.body.removeChild(paragraph);
document.getElementById('sign').hidden = true;
element.onclick = function() {
element.style.backgroundColor = 'blue'
};
You can also assign the .onclick property to a function by name:
function turnBlue() {
element.style.backgroundColor = 'blue';
}
element.onclick = turnBlue;
let eventTarget
= document.getElementById('targetElement');
eventTarget.addEventListener('click', function() {
// this block of code will run when click event happens
on eventTarget element
});
function eventHandlerFunction() {
// this block of code will run when click event happens
}
eventTarget.addEventListener('click',
eventHandlerFunction);
Removing Event Handlers
This method stops the event target from “listening” for an event to
fire when it no longer needs to. .removeEventListener() also takes two
arguments:
eventTarget.removeEventListener('click',
eventHandlerFunction);
EX:
let fortunes = ["A beautiful, smart, and loving person will be comi
ng into your life.",
"A fresh start will put you on your way.",
"A golden egg of opportunity falls into your lap this month.",
"A smile is your personal welcome mat.",
"All your hard work will soon pay off."
]
let button = document.getElementById('fortuneButton');
let fortune = document.getElementById('fortune');
function fortuneSelector(){
let randomFortune = Math.floor(Math.random() * fortunes.length);
return fortunes[randomFortune];
}
function showFortune(){
fortune.innerHTML = fortuneSelector();
button.innerHTML = "Come back tomorrow!";
button.style.cursor = "default";
button.removeEventListener('click', showFortune)
//add your code her
}
button.addEventListener('click', showFortune);
Event Object Properties
JavaScript stores events as Event objects with their related data and
functionalities as properties and methods. When an event is
triggered, the event object can be passed as an argument to the
event handler function.
function eventHandlerFunction(event){
console.log(event.timeStamp);
}
eventTarget.addEventListener('click',
eventHandlerFunction);
EX:
You’ve seen the click and wheel events, but, are more mouse events
to explore!
The mousedown event is fired when the user presses a mouse button
down.
The mouseup event is fired when the user releases the mouse button.
The mouseover event is fired when the mouse enters the content of an
element.
Keyboard Events
The keypress event is fired when a user presses a key down and
releases it.
Debugging Review
Instructions
------------------------------------//--------------------------
-
MODULES
module.exports
To create a module, you simply have to create a new file where the
functions can be declared. Then, to make these functions available to
other files, add them as properties to the built-
in module.exports object:
/* converters.js */
function celsiusToFahrenheit(celsius) {
return celsius * (9/5) + 32;
}
module.exports.celsiusToFahrenheit = celsiusToFahrenheit;
module.exports.fahrenheitToCelsius = function(fahrenheit) {
return (fahrenheit - 32) * (5/9);
};
The code snippet above demonstrates two ways of exporting
functions from a module. Let’s break it down:
require()
The require() function accepts a string as an argument. That string
provides the file path to the module you would like to import.
/* water-limits.js */
const converters = require('./converters.js');
const freezingPointC = 0;
const boilingPointC = 100;
/* celsius-to-fahrenheit.js */
const { celsiusToFahrenheit } = require('./converters.js');
Suppose you have a file and you wish to import all of its contents into
the current file. This can be done with the import * as syntax
myMathModule.add(2,3);
myMathModule.subtract(5,3);
------------------------------------//--------------------------
-
Likewise, synchronous code executes in sequential order — it starts with the code at the top
of the file and executes line by line until it gets to the end of the file. This type of behavior is
known as blocking (or blocking code) since each line of code cannot execute until the previous
line finishes.
It is our job as developers to think about how much time it takes to complete a task
and how to plan around that wait. Tasks like contacting the back-end to retrieve
information, querying our database for user information, or making a request to an
external server, like a 3rd party API, take varying amounts of time. Since we aren’t sure
when we’ll get this information back, we can use asynchronous code to run these tasks
in the background.
This is a type of callback function that executes after a specific condition is met and runs
concurrently to any other code currently running.
easterEgg.addEventListener('click', () => {
console.log('Up, Up, Down, Down, Left, Right, Left, Right, B, A');
});
In the code above, the function passed as the second argument of .addEventListener() is an
asynchronous callback — this function doesn’t execute until the easterEgg is clicked.
setTimeout
With setTimeout() we can write code that tells our JavaScript program to wait a minimum
amount of time before executing its callback function. Take a look at this example:
setTimeout(() => {
console.log('Delay the printing of this string, please.');
}, 1000);
The setTimeout() takes 2 arguments, a callback function and a number specifying how long
to wait before executing the function. In the example above, the function will print 'Delay the
printing of this string, please.' after 1000 milliseconds (or 1 second) have passed.
Since setTimeout() is non-blocking, we can be executing multiple lines of code at the same
time!
setTimeout(() => {
console.log('Delay the printing of this string, please.');
}, 1000);
console.log('Doing important stuff.');
console.log('Still doing important stuff.');
Which outputs:
In web development, this means we can write code to wait for an event to trigger all while a
user goes on interacting with our app. One such example could be if a user goes to a shopping
site and gets notified that an item is up for sale and only for a limited time. Our asynchronous
code could allow the user to interact with our site and when the sale timer expires, our code
will remove the sale item.
setInterval()
setInterval(() => {
alert('Are you paying attention???')
}, 300000)
The setInterval() would call the alert() function and show a pop-up message of 'Are you
paying attention???' every 300000 milliseconds (or 5 minutes).
While we wait for our alert to chime in every 5 minutes, our users could still use our app!
With setInterval(), we can programmatically create an alarm, a countdown timer, set the
frequency of an animation, and so much more!
----------------------------------------------------//--------------------------------------------------------
PROMISES
What is a Promise?
Promises are objects that represent the eventual outcome of
an asynchronous operation. A Promise object can be in one of three
states:
EXERCICIO:
const inventory = {
sunglasses: 0,
pants: 1088,
bags: 1344
};
const myExecutor = (resolve, reject) => {
if(inventory.sunglasses > 0) {
resolve('Sunglasses order processed.');
} else {
reject('That item is sold out.');
}
}
function orderSunglasses() {
return new Promise(myExecutor);
}
const orderPromise = orderSunglasses();
console.log(orderPromise);
Consuming Promises
Promise objects come with an aptly named .then() method. It
allows us to say, “I have a promise, when it
settles, then here’s what I want to happen…”
In the case of our dishwasher promise, the dishwasher will run then:
const inventory = {
sunglasses: 1900,
pants: 1088,
bags: 1344
};
const checkInventory = (order) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
let inStock = order.every(item => inventory[item[0]] >= item[1])
;
if (inStock) {
resolve(`Thank you. Your order was successful.`);
} else {
reject(`We're sorry. Your order could not be completed because
some items are sold out.`);
}
}, 1000);
})
};
module.exports = { checkInventory };
const inventory = {
sunglasses: 1900,
pants: 1088,
bags: 1344
};
const checkInventory = (order) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
let inStock = order.every(item => inventory[item[0]] >= item[1])
;
if (inStock) {
resolve(`Thank you. Your order was successful.`);
} else {
reject(`We're sorry. Your order could not be completed because
some items are sold out.`);
}
}, 1000);
})
};
module.exports = { checkInventory };
prom
.then((resolvedValue) => {
console.log(resolvedValue);
})
.catch((rejectionReason) => {
console.log(rejectionReason);
});
firstPromiseFunction()
.then((firstResolveVal) => {
return secondPromiseFunction(firstResolveVal);
})
.then((secondResolveVal) => {
console.log(secondResolveVal);
});
Using Promise.all()
myPromises
.then((arrayOfValues) => {
console.log(arrayOfValues);
})
.catch((rejectionReason) => {
console.log(rejectionReason);
});
----------------------------------------------------//--------------------------------------------------------
ASYNC AWAIT
myFunc();
EXERCICIO:
EXERCICIO:
function nativePromiseVersion() {
returnsFirstPromise()
.then((firstValue) => {
console.log(firstValue);
return returnsSecondPromise(firstValue);
})
.then((secondValue) => {
console.log(secondValue);
});
}
Here’s how we’d write an async function to accomplish the same thing:
Though using the async...await syntax can save us some typing, the
length reduction isn’t the main point. Given the two versions of
the function, the async...await version more closely resembles
synchronous code, which helps developers maintain and
debug their code. The async...await syntax also makes it easy to
store and refer to resolved values from promises.
Exercicio:
Handling Errors
But what if our async function contains multiple promises which are
not dependent on the results of one another to execute?
Exercicio:
Await Promise.all()
----------------------------------------------------//--------------------------------------------------------
HTTP Requests
Understand the basics of how your web browser communicates with the internet.
The internet is made up of a bunch of resources hosted on different
servers. The term “resource” corresponds to any entity on the web,
including HTML files, stylesheets, images, videos, and scripts. To
access content on the internet, your browser must ask these servers
for the resources it wants, and then display these resources to you.
This protocol of requests and responses enables you view this page in
your browser.
What is HTTP?
HTTP/1.1 200 OK
Content-Type: text/html
This header is followed by the content requested, which in this case is
the information needed to render www.codecademy.com.
The first line of the header, HTTP/1.1 200 OK, is confirmation that the
server understands the protocol that the client wants to communicate
with (HTTP/1.1), and an HTTP status code signifying that the resource
was found on the server. The second line, Content-Type:
text/html, shows the type of content that it will be sending to the
client.
If the server is not able to locate the path requested by the client, it
will respond with the header:
Upon arriving at the business, she asks the first of several free
employees ready to fulfill the request. The employee searches for the
page of the newspaper that you requested but cannot find it and
communicates that back to the mail delivery person.
The mail delivery person returns on the light speed train, ripping up
the tracks on the way back, and tells you that there was a problem
“404 Not Found.” After you check the spelling of what you had
written, you realize that you misspelled the newspaper title. You
correct it and provide the corrected title to the mail delivery person.
This time the mail delivery person is able to retrieve it from the
business. You can now read your newspaper in peace until you decide
you want to read the next page, at which point, you would make
another request and give it to the mail delivery person.
What is HTTPS?
Since your HTTP request can be read by anyone at certain network
junctures, it might not be a good idea to deliver information such as
your credit card or password using this protocol. Fortunately, many
servers support HTTPS, short for HTTP Secure, which allows
you to encrypt data that you send and receive.
----------------------------------------------------//--------------------------------------------------------
Types of APIs
There are two main categories of web APIs, browser APIs and 3rd
party APIs.
Making Requests
For example, when using the OpenWeather API, we need to provide
more information to search for weather information — such
information could include: the name of a city, time of day, the type of
forecast, etc. These specifications for making a request can also be
found in the API documentation.
Response Data
After we make a successful API request, the API sends back data.
Many APIs format their data using JavaScript Object
Notation (JSON) which looks like a JavaScript object. Here’s a
quick example of what JSON data might look like:
{
"temperature" : {
"celcius" : 25,
},
"city": "chicago",
}
It’s then up to us how to determine how to consume, or use,
this information in our apps. If we got back that sample JSON
above, we could parse out the temperature information and
display it on our app.
----------------------------------------------------//--------------------------------------------------------
What Is JSON?
As programmers, we need to be able to transfer our populated
data structures from any language we choose to a format that
is recognizable and readable by other languages and
platforms. Fortunately for us, there exists such a data-exchange
format.
What is JSON?
JSON, or JavaScript Object Notation, is a popular, language-
independent, standard format for storing and exchanging
data. JSON has become the de facto standard that facilitates
storing and sending data between all programming
languages.
When companies make their data public for other applications, like
Spotify sharing its music library or Google sharing its map
data, the information is formatted in JSON. This way, any
application, regardless of language, can collect and parse the data.
JSON Syntax
Since JSON is derived from the JavaScript programming language, its
appearance is similar to that of JavaScript objects.
{
"student": {
"name": "Rumaisa Mahoney",
"age": 30,
"fullTime": true,
"languages": [ "JavaScript", "HTML", "CSS" ],
"GPA": 3.9,
"favoriteSubject": null
}
}
Note the following syntax rules for JSON:
JSON property names must be in double-quoted (" ") text even
though JavaScript names do not hold by this stringency.
"2014-01-01T23:28:56.782Z"
This above format contains parts which resemble a date and time.
However, as a string, it is hard for a programming language to use as
is. Conveniently, every programming language has built-in
JSON facilities to convert this string into a more readable and
usable format, such as:
console.log(jsObject);
---------------------------------------------------------------//------------------------------------------------
Have you ever wondered what happens after you click a “Submit”
button on a web page? For instance, if you are submitting
information, where does the information go? How is the
information processed? The answer to the previous questions
revolves around HTTP requests.
There are many types of HTTP requests. The four most commonly
used types of HTTP requests are GET, POST, PUT, and DELETE.
With a GET request, we’re retrieving, or getting, information
from some source (usually a website).
First, call the fetch() function and pass it a URL as a string for the first
argument, determining the endpoint of the request.
fetch('https://api-to-call.com/endpoint')