Final P2 Flashcards
form tag itself has two very important attributes.
- Action which specifies where the form should be sent
2. Method which specifies the HTTP method to be used in the HTTP request sent when the form is submitted
percent-encoding or URL encoding
certain special characters that have a specific meaning within URLs are encoded with other characters
T or F: A GET request will send the same data as POST. But instead of sending it as part of the URL, it is sent in the body of the request.
False: A POST request will send the same data as GET. But instead of sending it as part of the URL, it is sent in the body of the request.
T or F: Unless we use the HTTPS protocol, which encrypts the HTTP communication, an intruder can see the body of a POST request.
True
T or F: even when using HTTPS protocol, we must not use GET for submitting sensitive data, such as passwords. Many web servers log the URL of HTTP requests, and putting sensitive data in the URL with GET requests can result in that data being saved in log files.
True
T or F: Another limitation of POST is that browsers often place a limitation on the length of the query string, whereas no such limits are placed on the body length.
False: GET
Processing a submitted form in ___ requires adding a route for the URL and HTTP method specified in the form. ___ then provides the data submitted in the form as a JSON object to our route handler function
Express
GET route handler example
app.get(“/review”, (req, res) => {
console.log(req.query);
res.send(req.query);
});
POST route handler example
app.post(“/review”, (req, res) => {
console.log(req.body);
res.send(req.body);
});
app.use(express.urlencoded({
extended: true
}));
T or F: CSS is a language for describing the presentation of documents. It allows us to specify rules using which we can selectively style HTML elements. Typically we write these CSS rules into stylesheets which are files containing CSS rules.
True
CSS selector
selects the HTML element to which the rule applies
CSS format
h1 {
color: red;
font-size: 25pt;
}
CSS: The universal selector *
matches all elements
CSS: The ___selector matches elements based on the element ___
type
CSS: The ___ selector selects the single element with a matching __ and is of the form #id
ID
CSS: The ___ selector selects all elements in which the attribute class has that value
class
T or F: IDs are good for anchoring and specifying unique blocks, whereas classes are more about design properties that get used again and again.
True
CSS: Is it possible to specify rules that apply to multiple selectors.?
Yes, This is done by specifying multiple selectors separated by commas.
CSS: We can specify selectors that select elements based on their location in the document
combinator selector
CSS: We can combine selectors to form more complex selectors. A common use is combining a type and a class to specify a selector that applies to tags with that type but only if they have that particular class. The syntax for this is tag.class.
Complex Selector
CSS also supports selectors that are based on the state of an element
CSS Pseudo Selectors
selector:pseudo-class {
property: value;
}
T or F: Common use cases for CSS pseudo-classes are changing the style of an element when the mouse hovers over it, and displaying visited links differently from links that have not been visited.
True
CSS: Rule Precedence
- Later rules overrule earlier rules.
2. Rules with a more specific selector take precedence over those with more general selectors.
Colors in CSS are represented in three ways.
- Hex (hexadecimal) values in the form of #RRGGBB.
- Decimal values in the form of rbg(x, y, z)
- Named colors
T or F: In CSS, the absolute units are not relative to anything, whereas the relative units are relative to something else, e.g., the size of the parent element.
True
The most commonly used relative units are __ and __.
- em
2. rem
T or F: em is a relative unit based on the current font size of the parent element. For example, 2em means two times the parent element’s current font size.
True
T or F: rem is a relative unit based on the current font size of the root element. For example, 2rem means two times the current font size of the root element.
True
Size Properties in the Box Model
- Element (width/height)
- Padding (padding-top, etc.)
- Margin (margin-top, etc.)
- Border (can specify color, style, width)
T or F: 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.
True
T or F: With relative positioning, the browser figures out where something should to be positioned using its default positioning algorithm.
False: static
T or F: Elements with static positioning are moved in relation to where they would be placed by the static positioning.
False: relative
T or F: Elements with absolute positioning are positioned in relation to the parent element.
True
T or F: Elements with fixed positioning are positioned with respect to the document window
True
T or F: As a first step to rendering a page, the browser parses the HTML document and creates a DOM tree from it. From there the browser renders the page by rendering each node of the DOM tree.
True
T or F: The DOM (Document Object Model) is the model that a browser uses to render a web page
True
T or F: The DOM gives a representation of a document as a logical tree of nodes and includes an API for interacting with this tree representation. This allows us to write programs to statically access and modify the content, structure, and style of an HTML document.
False: This allows us to write programs to DYNAMICALLY access
T or F: Versions of DOM are referred to as levels. When we read the DOM specification on the W3C website we will find a description of interfaces rather than the description of the API in a particular programming language.
True: This is because the DOM specification is programming language neutral. Many programming languages have implemented the DOM specification so that programs written in that language can use the DOM API.
T or F: The object ___ represents the browser window and the object ___ represents the webpage currently loaded in this browser window.
- window
2. document
T or F: The object document gives us an entry point into the DOM tree that the browser has built up after it parsed the webpage.
True
DOM tree includes nodes of the following type:
- Document
- Document Type
- Element
- Attribute
- Text
Any node that has one or more children has the following properties:
- firstElementChild
- lastElementChild
- nextElementSibling
- previousElementSibling
- children
- parentNode
T or F: All of these are methods for searching for elements:
- getElementById
- getElementsByTagName
- getElementsByClassName
- querySelector
True
T or F: Probably the most basic property of a node is its textContent. This contains all the text content of a node, and its children, in a string representation.
True
T or F: Setting a node’s textContent to an empty string will clear out all of its text and that of its child nodes.
True
Nodes of type element have a property named ___which get the HTML markup within an element.
innerHTML
As we can see ___ of this p element contains its text content and that of its child element b concatenated as a string, but it does not contain the HTML tags or the attribute. On the other hand, the ___ property contains all the HTML content, including the tags of child elements and attributes inside the element book.
- textContent
2. innerHTML
T or F: Using the property innerHTML to insert text into a webpage is a security risk. It is recommended that the insertion of plain text should be done using textContent and should not use innerHTML
True
Adding nodes in a DOM tree is a two step process:
- Create the node by calling the appropriate method on the document object.
- The newly created node does not yet appear in the DOM tree. As the second step, we insert the new node at the desired position in the DOM tree.
T or F: The method document.createTextNode() can be used to create new text nodes. However, in most cases we can simply add text content using the textContent property we discussed earlier, rather than creating a text node.
True
T or F: To create elements we use the method document.createElement().. It takes one argument which is the name of the element we want to create and returns an element of that type. However, the newly created element does not yet exist in the DOM tree.
True
T or F: There are many different methods available to insert nodes in a DOM tree, but one of the most common ways to insert elements is calling the method appendChild(newChild) on a node. This method will add the node newChild as the last child of the node the method was called on.
True
the method ___ and pass it the node we want to remove as an argument
removeChild()
When a user takes an action, the browser dispatches an event based on the type of user action. We can use JavaScript to register functions called event handlers. What type of programming is this?
event-driven programming
T or F: When an event of particular type occurs, the browser executes the event handler registered for that type of event. We can program event handler functions so that they modify attributes of DOM nodes, modify the DOM tree or send HTTP requests to a webserver, thus providing interactivity in our application.
True
Event handling requires specifying 3 things
- What happened, i.e., what is the event of interest?
- Where did this event occur, i.e., what is the element of interest?
- What to do, i.e., what JavaScript code to invoke when the event occurs on this element?
Types of DOM events that should be handled
- mouse-related events
- keyboard-related events
- focus-related events
- form submission events
- Input event
- page related events
- timer events
There are two ways to register an event handler to execute when an event occurs on an element.
- Register the JavaScript code inline, as the value of an attribute with the name of the event (not recommended).
- Register the JavaScript code using the DOM API.
Registering an event handler on an element: Register the JavaScript code using the DOM API format
myElem.addEventListener(‘click’, mouseClick)
Example: Registering an Event Handler
// The browser can pass the event to the event handler function mouseClick(event) { console.log('Mouse clicked on the following element'); // The property event.target is set to the element which dispatched // the event. We will discuss this and other properties of // event in the next section. console.log(event.target); // If the color is currently red, set it to green. // Otherwise set it to red. event.target.style.color = event.target.style.color === 'red' ? 'green' : 'red'; };
window.onload = function () { document.getElementById('registerWithDOM').addEventListener("click", mouseClick); };
T or F: We remove an event handler from an element by calling the method removeEventListener on this element.
True
Example: Removing an Event Handler
function unbindButton() { document.getElementById('backgroundChanger').removeEventListener('click', changeColor); }
T or F: When an event is raised, the browser cannot pass an object corresponding to this event to our handler.
False, it can
Some of the most important properties of this object include the following:
- type: the name of the event, e.g., click, mouseup, etc.
- timeStamp: the time that the event was created.
- target: the element that dispatched the event.
- currentTarget: the element on which the event listener was registered.
T or F: Load events are called when a resource and all of its dependent resources have finished loading. When we want some JavaScript code to execute as soon as a resource is loaded, we can register a handler with that JavaScript code to the corresponding load event.
True
Load Event Example: A common use case is when we want to manipulate a webpage as soon as it is loaded.
document.addEventListener(“DOMContentLoaded”, function(event) {
console.log(“DOM fully loaded and parsed”);
});
___ provide another mechanism for event-driven programming in JavaScript. These ___ are used in client-side code for animations or for automatic page refreshes.
Timers
Timer example
setTimeout(turnBackgroundRed, 10000);
We can call the method ___ () on an event to prevent the default action for the event from taking place.
An example use case is calling this method on a submit event to prevent the submission of a form if the form validation fails, as shown in the following code snippet.
preventDefault
When an event is fired at an element that has parent elements, what happens if event handlers are defined at both the element and its parent?
The default behavior is that the event bubbles up the DOM tree until it gets to the root element, i.e., the html element. This is called the bubbling phase.
The event handler on any element can stop an event from bubbling up the DOM tree by calling the method of the event in question.
stopPropagation
Is it also possible to define event handlers which are executed on the DOM tree starting with the html element and going down the tree until the element on which the event occurred is reached?
Yes, This is called the capturing phase and the event is said to trickle-down the DOM tree. Using stopPropagation stops an event from trickling down the DOM tree, similar to how this method stops an event from bubbling up. By default, event handlers are registered for the bubbling phase and registering handlers for the capturing phase is a lot less common.
___ programming is an essential feature of modern JavaScript. It is widely used to build scalable, performant web apps. ___ features of JavaScript are used in both client-side and server-side programs.
Asynchronous
By default, JavaScript code run ___ in a single thread
synchronously
Asynchronus or Synchronous?
Each function runs to completion before any other code is executed in the program.
Synchronous
___ means that the entire program is halted until that line of code finishes executing.
Blocking
Asynchronus or Synchronous?
non-blocking. As soon as an ___ function is called, the next line of code in the calling function can be executed.
Asynchronus
T or F: When the asynchronous function completes, its results can be accessed by the main thread using callbacks or via the newer features of Promises and await/async.
True
Why Using Callbacks is Unsatisfactory
when our program needs to make multiple asynchronous calls that depend on each other (nested), implementing asynchronous functionality using callback functions can lead to hard-to-understand code
A ___ is a JavaScript object that represents the result of an asynchronous operation whose results may not be available as yet.
Promise
When the asynchronous function successfully finishes, it fills in the Promise object with the result and sets its state to ___ . The promise is now said to have been ___ . The Promise is said to have resolved to this result value.
fulfilled
The asynchronous function returns a ___ object.
Promise
The initial state of this Promise object is ___ meaning it does not yet have a result.
pending
When the asynchronous function fails due to an error, it will not produce a value. In this case, the state of the Promise object is set to ___. The promise is said to have been ___.
rejected
Once the state of the Promise objects is set to either the fulfilled or rejected, it is said to have been ___.
settled
T or F: When we call a function which returns a promise, we provide functions that will be executed when the promise settles.
True
Using the ___ method on the promise, we provide a function that will be called when the promise returns a result, i.e., it is fulfilled. If the function provided to ___ returns another promise, we can process its result by calling the ___ method again
then()
Using the ___ method on the promise, we provide a function that will be called when the promise fails, i.e., it is rejected.
catch()
The function ___ has one required parameter identifying the resource for which an HTTP request would be sent. By default, ___ sends a request with the GET method. ___ returns a promise.
fetch()
fetch() example
function getData(url) {
return fetch(url)
.then(response => response.text())
.then(data => addData(data))
.catch(error => console.error(error));
}
when one asynchronous function returns a promise which is then passed to another asynchronous function that in turn returns a promise, we can chain these function calls by using multiple ___ methods.
then()
The ___ keyword takes a promise and waits for the promise to be settled. If the promise is fulfilled, the resolved value is returned.
If the promise is rejected, an exception is thrown with the rejection value of the promise.
await
we can only use ___keyword in a function that is declared with the ___ keyword
await
async
An ___ function is executed asynchronously which means that the call to the ___function returns immediately. A __ function always returns a promise.
async
async example
async function getData(url) { try { const response = await fetch(url); const data = await response.text(); addData(data); } catch (error) { console.error(error) } }
When we write code in an ES module, only those functions, classes or variables that are explicitly exported using the keyword export are available outside the module. Such exports are called named ___. Everything else is inaccessible to code outside the module.
exports
We ___ named features from a module using the ___ statement along with the name of the features we want to ___ and the URL of the file containing the module.
import
We can import all the exported features into an object by using __.
*
We can tag at most one feature in an ES module with the export ___ tag. The benefit of default exports is that the syntax for importing the default feature is very simple.
default
With CommonJS modules, we import features using the ___ built-in function. This function takes one argument which identifies the module or the local file we want to import into our code.
require()
In CommonJS, the function ___ reads the module/file passed to it as an argument. It executes this module/file and returns the ___object from the file.
require()
exports
IUSING ES Modules with node:
Use the extension \_\_ for files which want to export modules using ES syntax and for files which want to import modules using ES syntax. Use the extension \_\_ for such files and also add a top level property "type" with the value "module in the file package.json.
.mjs
.js
Express: To serve static files, we added the following statement to our server programs:
app.use(express.___(‘public’));
static
Express: When our server program needed to process forms, we added the following statement to our program
app.use(express.___({extended: true}));
urlencoded
A ___is simply a function that Express applies to an HTTP request in our Express programs. We can think of an Express program as a pipeline of ___functions which are applied to an HTTP request.
middleware
Most middleware functions take three arguments:
- request
- response
- next()
Another form of middleware functions, called Error-handling middleware, takes four arguments:
- error
- request
- response
- next()
Each middleware function in an Express app is associated with a ___(or route). A middleware function applies to an HTTP request only if that function’s ___matches the URL of the request.
path
T or F: The middleware functions with routes matching a request’s URL are applied in the exact order of how they appear in the code of our Express app, thus setting up a pipeline of functions.
True
A middleware function can pass the request to the next middleware function in the pipeline by calling the ___ function that is provided to it as an argument.
next()