A Brief History of the Web
1963 – Ted Nelson coined term hypertext. Text linked content
1969 – ARPANET
First Real Packet Switched Network
Under Contract from ARPA by BBN of Cambridge, MA and under Bob
Kahn
Connected mostly a handful of Universities First link UCLA and Stanford
1972 – Email adapted for ARPANET
Ray Tomlinson of BBN, choose @ to separate name and host
1973-74 – TCP
Bob Kahn at DARPA and Vint Cerf at Stanford develop TCP
1978 TCP finalized into TCP/IP
A Brief History of the Web
1980 - Tim Berners-Lee at CERN creates ENQUIRE
personal database of people and software models
simple Hypertext program
1983 – ARPANET switches over to TCP/IP from NCP
1984 – DNS system
made addresses on the Internet more human-friendly
1987 – About 30,000 hosts on Internet
A Brief History of the Web
1989 – Tim Berners-Lee of CERN develops a new technique for
distributing information on the Internet.
Information Management: A Proposal
Based on Hypertext
Called it the World Wide Web
http://www.w3.org/History/1989/proposal-msw.html
1990 - World Wide Web concepts defined, protocols and technologies
HTML, HTTP, and URLs
Aug 6, 1991 - First web page created for project on info.cern.ch
http://www.w3.org/History/19921103-
hypertext/hypertext/WWW/TheProject.html
A Brief History of the Web
1993 - Mosaic – first major graphical web browser to make the
Internet accessible to non-techies
Developed by Marc Andreeson and team at the National Center for
Supercomputing Applications (NCSA), University of Illinois
Later forms Netscape
1994-95
CompuServe, America Online, and Prodigy start providing dial-up
Internet access.
Netscape develops Navigator Browser and SSL
Sir Tim Berners-Lee founds the World Wide Web Consortium (Oct 94)
A Brief History of the Web
1995 continued
Ebay, Amazon, Vatican, Geocities all go online
Sun releases Java programming language
JavaScript created by Brendan Eich (originally called LiveScript) is
released as part of Netscape Navigator
1996 – HoTMalL, First webmail
1997 – Weblog term coined
NASA pathfinder sets traffic record with over 200 million views
between July 4-8, 1997
A Brief History of the Web
1998 – Google goes live
1999 – Napster
2001 – Wikipedia
2004 – Facebook
2005 – Youtube
2006 – Twitter
Nov 2006 – 100 Million Websites
2007 – iPhone brings era of mobile web
Sept 2014 – 1 Billion Websites
HTML
HyperText Markup Language
Created by Tim Berners-Lee while working at CERN
Wrote the original internet-based hypertext system proposal memo in 1989.
https://www.w3.org/History/1989/proposal.html
First description of HTML was a document called “HTML Tags” in 1991.
https://www.w3.org/History/19921103-hypertext/hypertext/WWW/MarkUp/Tags.html
Strongly influenced by CERN SGML (standard generalized markup language) based system in use
at CERN
HTML elements become the building blocks of HTML pages.
He created HTML and HTTP protocol
Set of nested “tags” that look like xml and is a markup language, not a programming language
This provides a way to make structured documents with structural semantics like headlines,
paragraphs, links, lists, and other items. Tags either directly insert content in the page or wrap
around content to provide additional information.
HTML is the STRUCTURAL layer of a web page
HTML
Major Version History
HTML Tags – Informal CERN document with 18 tags, October 1991
HTML 1.1 – First draft with a version number, November 1992
HTML 2.0 – Published as IETF RFC 1866, November 1995
HTML 3.2 – Published as W3C recommendation, January 1997
HTML 4.0 – Published as W3C recommendation, December 1997 and reissued in April
1998 with minor edits
HTML 4.1 – Published as W3C recommendation, December 1999
HTML 5 – Published as W3C recommendation, October 2014
XHTML 1.0 – Published as W3C recommendation, January 2000 and revised in April
2002
XHTML 1.1 – Published as W3C recommendation, May 2001 and based on XHTML 1.0
Strict
XHTML 2.0 – Was a working draft but abandoned in 2009 in favor of HTML5
CSS
Cascading Style Sheets
A style sheet language used to describe how the markup should look and be
presented to the user in the browser.
First proposed in October 1994 by Håkon Wium Lie, Norwegian, while working with Tim
Berners-Lee and Robert Cailliau at CERN.
Arena web browser became the first to implement CSS
He joined W3C in 1995 to work on CSS Specifications with Bert Bos
Wium Lie became an activist for web standards, including challenging Microsoft to
support web standards.
Robert Cailliau wanted to separate the structure (HTML) from the presentation (CSS)
to allow for more flexible presentation of the same content
Original browsers/editors had the “style sheets” hard coded into the programs so
consistency between different browsers was difficult.
Proposals were being presented in 1994-1995 and by 1996 CSS level 1 was published
as a recommendation.
CSS
Used to apply visual styles to a web page and its structure
CSS is the PRESENTATION layer of a web
CSS 1 – Published as a recommendation December 1996
CSS 2 – Published as a recommendation May 1998
CSS 2.1 – Published as a recommendation June 2011
Single large specification, fixed errors in CSS 2
Went back and forth from working draft to candidate recommendation for many years
CSS 3 – Current standard being developed
Full specification is split up into modules
Comprised of many small modules in working drafts
Started being worked on when CSS 2 was published
Earliest CSS 3 drafts were June 1999, working draft was started in 2001
https://www.w3.org/TR/2001/WD-css3-roadmap-20010523/
https://www.w3.org/Style/CSS/specs.en.html
CSS
CSS History Resources
https://en.wikipedia.org/wiki/Cascading_Style_Sheets
https://www.w3.org/Style/CSS20/history.html
https://css-tricks.com/look-back-history-css/
Stop Here on Day 1
Day 2 will begin with an overview of the Syllabus in detail
JavaScript
JavaScript – ECMA compliant Object-Oriented language
http://en.wikipedia.org/wiki/JavaScript
JavaScript or JS is the BEHAVIOR layer of your web page
JavaScript is a programming language
It is capable of the following
Animating page elements, modifying the DOM, updating content with AJAX
Manipulating HTML tags and CSS rules
Interactive elements like games and video
Validate forms
Implementing browser APIs like location and local storage
And much more...
JavaScript
Originally developed by Brendan Eich at Netscape
Prototyped in a 10-day period in May 1995
Developed with code name Mocha, then officially called LiveScript in beta Netscape Navigator
2 in Sept 1995.
Renamed JavaScript before final release of Netscape Navigator 2 (B3). Marketing ploy by
Netscape to cash in on the popularity of the new language Java which was also included in
Netscape 2. Was initially planned on being a lightweight glue language to connect Java to the
browser. Released in Joint press release in Dec 1995.
November 1996 – Netscape submitted JavaScript to Ecma International to be considered a
standard.
June 1997 – Ecma International published the ECMA-262 Specification in version 1.
2008-2009 there was an agreement to combine all the vendors work and move forward with the
language. The result was ECMAScript 5 standard. ECMAScript 5.1 standard was published in June
2011. This was a widely supported standardized version of the language.
https://en.wikipedia.org/wiki/JavaScript
ECMAScript 6 published June 2015, ECMAScript 7 published June 2016, ES13 published June 2022
https://en.wikipedia.org/wiki/ECMAScript
JavaScript
We are always working towards new versions of JavaScript
ECMAScript 6th Edition – 2015 Language Specification was a major
update
Adds new syntax and features
All current browsers offer direct support at this point but there may
be some newer features not supported
Can compile ES6+ to ES5 with many available tools
We will discuss some differences later in class
Most recent version is 13th Edition, June 2022
https://www.ecma-international.org/publications-and-
standards/standards/ecma-262/
Browser Development Tools
Browser Development Tools
Built into all major browsers now
Provide a way to inspect a page, modify CSS, interact with a
JavaScript Console, profile, monitor network requests, and more.
Chrome Dev Tools
https://developer.chrome.com/docs/devtools/
Let’s look at some of the options in the browser dev tools
HTTP
Hypertext Transfer Protocol (HTTP)
First designed by Tim Berners-Lee at CERN
OSI and TCP/IP application layer protocol for transporting HTML
documents and other hypermedia across the internet
Client-sever protocol that works on a request-response concept
Designed as a stateless protocol - no state (data) link between two
requests on the same connection
Addition of HTTP cookies allows stateful sessions
Simple text-based protocol
Uses port 80 by default
HTTPS
Hypertext Transfer Protocol Secure (HTTPS)
HTTP protocol extension
First created in 1994 by Netscape Communications for the Netscape
Navigator web browser
HTTP through an encrypted SSL/TLS connection
Originally used the SSL (secure sockets layer) protocol to add
encryption
SSL evolved into TLS (transport layer security)
SSL went from version 1 to 3 in a couple years to fix problems and TLS 1.0
was first defined in 1999
SSL 3 was depreciated in June 2015 and TLS 1.0 and 1.1 were
deprecated by all major vendors in March 2020
TLS 1.3 is the most recent version
HTTPS
Uses public and private keys to generate and encrypt a short-term
session key which is used to encrypt/decrypt the data.
Certificate authorities and public key certificates are used to verify
the owner and validity of a key
TLS Handshake occurs and the client and server agree on the
ciphers and other parameters. Then the client encrypts a random
number using the server’s public key and they both generate a
session key that is used for encryption and decryption of data
Regular HTTP protocol is then sent through the encrypted
connection
Uses port 443 by default
HTTP/0.9
Tim Berners-Lee’s first documented version of HTTP in 1991
https://www.w3.org/Protocols/HTTP/AsImplemented.html
Initially didn’t have a version number, later called HTTP/0.9
Only defined a single HTTP method, GET
One-line protocol
GET followed by resource path
GET /index.html
Response was the contents of the file
HTTP/1.0
In 1995 Dave Raggett led an HTTP working group to expand the
protocol by adding additional methods and headers and formalize
all the draft specifications.
This became HTTP V1.0 in 1996. It defined 3 methods GET, HEAD, and
POST
Appended HTTP version info to the end of the first line of the request
Status code was added to the first line of the response
Added headers for extensibility
Content-Type header allowed for files other than HTML
HTTP/1.1
First standardized version of HTTP
HTTP 1.1 was released in January 1997 and added 5 methods:
OPTIONS, PUT, DELETE, TRACE, and CONNECT.
It made the HOST header required.
Allowed a connection to be reused to save time.
Content negotiation introduced.
In 2007 the HTTP working group formed to clarify parts of the HTTP 1.1
specification and in June 2014 released an updated 6-part HTTP 1.1
specification.
HTTP/2
Protocol to increase performance standardized in May 2015
Built on Google’s experimental protocol SPDY in 2010’s
Binary protocol versus a text protocol.
Multiplexed protocol. Parallel requests over same connection.
Adds data compression for HTTP headers and server push
High-level compatibility with HTTP/1.1
methods, status codes, headers, URIs
Websites and applications did not require changes which lead to fast
adoption
https://en.wikipedia.org/wiki/HTTP/2
https://web.dev/performance-http2/
HTTP/3
Third major version of HTTP
Standard published on June 6, 2022
Semantically like previous versions using same request methods,
status codes, and message fields (headers)
Major difference is uses QUIC (transport layer protocol) over UDP
(User Datagram Protocol) instead of TCP
Can be 3x faster than HTTP/1.1 in some instances
https://en.wikipedia.org/wiki/HTTP/3
HTTP Request/Response
Individual requests are sent by a client to a server
We call the client a user agent and it is typically a web browser, but
can be any program that understands HTTP like a search engine web
crawler or CLI like curl
The server handles the request, processes it, and provides a response
The request is text formatted (pre http/2) data in a specific format that
can be as short as two lines of text.
Method and the resource being requested
Host header saying the domain it if being sent to, required as of 1.1
Each line ends with a carriage return (cr) followed by a line feed (lf) and the
entire request ends with a double newline
A Request body may follow the headers if the request is sending data
Response follows a similar format
What is a URL?
URL or Uniform Resource Locator
Just an address for a unique resource on the web
URL is made of of different parts
https://developer.mozilla.org/en-
US/docs/Learn/Common_questions/What_is_a_URL
Image from https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL
HTTP Request
Requests contain:
HTTP method for the operation the client is
trying to perform.
Path of the resource, no protocol, domain,
or port
HTTP protocol version
Headers for additional information (optional)
Request body for some methods like POST
Images from https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview
HTTP Response
Response contains:
HTTP protocol version
Status code representing if the request was
successful or not and the reason.
Status message. A short description of the
status code.
Headers for additional information
(optional)
Response body that contains the fetched
resource if there is content returning to
client.
Images from https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview
HTTP Flow
Client opens a TCP connection to the server
May be a new or existing connection
May open several connections
Sends an HTTP request message
Server processes request and sends response message to client
Client reads response send by server
Client closes or reuses the connection for other requests
Client sends request for each needed resource on page
HTTP Methods
HTTP Methods
GET, POST, PUT, DELETE, HEAD, CONNECT, OPTIONS, TRACE, PATCH
GET and POST are most common
GET
Request for a specified resource
Should only be used to retrieve data
Any data is sent as part of URL using query parameters
http://www.domain.com/?q=232&name=joe
Data q=232 and name=joe is available to target resources
HTTP Methods
POST
Submits data to a specified resource and often causes changes in data
state on the server
Almost always used to send form data
Any variable or form data is sent in the request body and not
appended to the URL
Type of data in request body would be indicated by the
Content-Type header
HTTP Methods
PUT
Replaces data or resource on the server with request content
Not used in HTML forms
DELETE
Delete specified resource
Not used in HTML forms
Used more with AJAX, frameworks, and non-browser HTTP requests
HTTP Methods
HEAD
Just like a GET request but only returns headers and not the body
OPTIONS
Requests communications options from server
CONNECT
Starts a two-way communication with a resource
TRACE
Performs a loop-back test for debugging
PATCH
Partial modifications to a resource
HTTP Status Codes
2xx – Successful
200 OK
The request succeeded. Exact details depend on method.
201 Created
The request succeeded and new resource was created.
Typically sent as a result of POST or PUT
HTTP Status Codes
3xx – Redirection
301 Moved Permanently
URL of requested resource has permanently moved, and the new URL is
given in the response. Search engines should update and use new URL.
302 Found
URL of requested resource has moved temporarily, and the new URL is
given in the response. May change again in the future so the same URL
should be used.
304 Not Modified
Requested resource has not been modified. Used to help caching.
HTTP Status Codes
4xx Client error
400 Bad request
Incorrect request syntax
401 Unauthorized
Client not allowed access to resource
May change if client retries with authentication
403 Forbidden
Client not allowed access to resource
Client identity is known to server and further authentication will not help
404 Not found – Dead link
HTTP Status Codes
5xx Server error
500 Internal Server Error
Something went wrong inside the server, or it doesn’t know how to
process
501 Not Implemented
The request is not supported by the server
503 Service Unavailable
Server not able to handle the request
Usually happens when a server is overloaded or down
HTTP Cookies
A HTTP Cookie is a small amount of text data that can be sent from the server in
a response and stored in the client.
The browser can then send the data back to the same server on future requests
This allows the server to know if two requests came from the same client
This is what allows our stateless HTTP protocol to be able to remember
information like keeping a user logged in.
Cookies are primarily used for session management, personalization, and
tracking
Cookies are set in a response using a Set-Cookie header and returned to the
server by the client automatically in a request using the Cookie header
Should not be used to store general data in the client, there are modern APIs
https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
Git
Git is an open-source distributed version control system
Track changes in a set of files
Originally author was Linus Torvalds in 2005 for use developing the
Linux kernel
Different than client-server VCS systems, every Git directory is a full
copy of the repository with history and version tracking without a
central server
Commits are stored with a cryptographic authentication history
Modified files are staged and then can be committed to the repo
CLI and GUI implementations
https://git-scm.com/about
Git Basics
Create a local repository from a folder with the init command
git init
Clone a remote repository from a location to a local copy
git clone [url]
Browse and inspect the history of the commits
git log
Stages a file to prepare it for a versioning commit
git add [file]
Commits staged files to the repository
git commit -m “[description]”
Git Basics
Show stage and commit status
git status
Branches can be created and merged
git branch [name]
git merge [name]
git checkout [name] or git switch [name]
Synchronize changes
git fetch, git merge, git push, git pull
https://training.github.com/downloads/github-git-cheat-sheet/
Visual Git Flow
GitHub
Web service that is used to host Git repositories and facilitate sharing
and social coding
Founded in Feb 2008 and launched in April 2008
Largest of the source code hosting platforms
Allows for public or private repositories
Purchased by Microsoft in June 2018 for $7.5 billion
Integrates hosting, version control, issue tracking, discussions
Code suggestions with pull requests
GitHub
GitHub Pages launched in 2008
Static web hosting service
Content stored in a GitHub repository
Serve files directly, parse markdown, or integrate with Jekyll
Gist launched in 2008
Hosting for small code snippets instead of projects
Way to share snippets with other uses or elsewhere on the web
Hosted as a repository
https://en.wikipedia.org/wiki/GitHub
https://github.com/
Git Resources
Git website and official book
https://git-scm.com/
https://git-scm.com/docs/gittutorial
Git Cheat Sheets
https://training.github.com/
GitHub getting started with Git
https://docs.github.com/en/get-started
https://docs.github.com/en
Lots of Git tutorials on YouTube
HTML
HTML (HyperText Markup Language)
Markup language that defines the structure of a web page and its
content
Made up from a series of nested elements
Elements are made from tags and content
https://developer.mozilla.org/en-
US/docs/Learn/Getting_started_with_the_web/HTML_basics
HTML Element
Opening Tag
Name of the element wrapped in
opening and closing angle brackets
Closing Tag
Similar to opening tag but has a forward
slash before the element name
Content
Element content, can be text, images,
or other elements
Element
Opening and closing tags and content
Images From: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics
HTML Attributes
Attributes add extra data to the element that does not visibly
appear on the page
Should include
Space between it and element name or any other attributes
Equal sign after the attribute name
Attribute value immediately after the equal sign wrapped in quotes
Quotes around attribute value are not required if the value doesn’t
have whitespace or special characters. It is good form to always
quote the values anyway for consistency and understandability.
Images From: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics
HTML Attributes
All HTML elements have general and specific attributes
For example, an anchor element (a) has a href attribute that points to
the location of the link. An image element (img) has a src attribute that
points to the source of the image.
All HTML elements have a class and id attribute
Class
Non-unique identifier that can be used for targeting with styling or other
reasons
Can be reused on a page, and element can have multiple class values
id
Unique identifier that can be used for targeting with styling or other reasons
Must be unique on the page, and element can only have one id
Boolean attributes may or may not have a value
HTML Elements
Two main categories of HTML elements
Block elements
Appear as new line on the page
Visible “Block” that spans the width of the page
Typically, structural elements: heading, paragraphs, lists, div, etc.
Block elements generally should not be nested in an inline element
Inline elements
Contained in a block element and wrap smaller amounts of content
Typically used with text elements. Things that flow with the content.
Behavior can be changed with CSS but still in same category
HTML Elements
Some HTML elements are ”empty” and do not contain content
Image is a good example
<img src="url-to-image">
No content and no closing tag
HTML can have comments
<!– comment here -->
HTML5 Page Structure
*You may still see the following meta tag, but it should be unnecessary at this point, it
was a tag for IE version < 11. Some template generators still add it.
<meta http-equiv="X-UA-Compatible" content="IE=edge">
Basic Tag
Here are some basic HTML elements you should already be familiar with
Headlines: h1, h2, h3, h4, h5, h6
Paragraphs: p
Anchor: a
Lists: ul, li, ol
Images: img
Bold and Italic: strong, em
General block: div
General inline: span
Basic Forms: form, input, textarea
We will talk about more later, including HTML5 specific ones
HTML5 Semantic Structural Elements
HTML5 provides semantic tags to give areas of your page structural
meaning
main – dominant content of the <body> of a document
article – self contained content that could be reusuable
section – generic standalone section in document
aside – content not directly related to main content
header – introductory content that groups content or nav
nav – section of the page meant for navigation
footer – a footer grouping for its nearest ancestor
https://developer.mozilla.org/en-
US/docs/Learn/HTML/Introduction_to_HTML/Document_and_website_str
ucture
CSS
CSS (Cascading Style Sheets)
Style sheet language, not markup or code, that you use to decorate
or style HTML elements
Consists of rules that define what should be selected and what
styling properties should apply
https://developer.mozilla.org/en-
US/docs/Learn/Getting_started_with_the_web/CSS_basics
CSS
These are the three primary ways to use CSS on a page in order of
preference.
Inline
CSS is added directly to an element using the style attribute on the tag
Embedded
CSS is added to the head section of a page using the <style></style> tags
External
CSS is added to the page with an external file reference using a link tag
This should be in the head section
<link href="styles.css" rel="stylesheet">
CSS Ruleset
Selector
Defines what elements this rule
applies to
Many different types of selectors
Property
Property value
Declaration
A property and value in a rule
Images From: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics
CSS Position
https://developer.mozilla.org/en-
US/docs/Learn/CSS/CSS_layout/Positioning
Positioning allows you to change the way elements interact and display
compared to the normal document flow
Static – default normal flow
Relative – puts the element in normal flow but allows you to move it after
Absolute – takes element out of the flow and positions it to the first parent
that has a positioning context
Fixed – positions element based on browser viewport
Sticky – newer combination of relative and fixed
CSS Box Model
https://developer.mozilla.org/en-
US/docs/Learn/CSS/Building_blocks/The_box_model
box-sizing
Standard Model
Padding and border is added to set
any width or height
Border Box Model
Padding and border is included in
any set width and height
Some properties only work on block or
inline boxes
Images From: https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model
CSS Cascade
https://developer.mozilla.org/en-
US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance
This determines how the rules flow and override each other
Cascade
The origin and order of the CSS rules
Specificity
Algorithm that browsers use to decided what rules to use on an element
if multiple selectors apply
Inheritance
Some CSS properties on a parent element are inherited to a child and
some are not. (mostly text things)
CSS Specificity
Based on a point scoring system
id – 100 points
class – 10 points
element – 1 point
Inline styles can be considered
1000
Images From: https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance
CSS3
Newest standard being developed
Unlike CSS2, CSS3 was split into smaller modules that could be
developed and published independently
https://www.w3.org/Style/CSS/Overview.en.html
https://www.w3.org/Style/CSS/specs.en.html
Includes new properties and features such as
CSS Selectors, border radius, box shadow, box sizing, opacity,
gradients, multiple backgrounds, transitions, transforms, animations,
flexbox, grid, media queries, variables, and more.
https://en.wikipedia.org/wiki/CSS
https://www.css3.info/modules/
CSS Variables
CSS custom properties or variables have been added as part of CSS3
Allows you to define a custom property with a value and reuse it
Typically defined on the :root pseudo-class and they inherit all the way down but
doesn’t have to.
Begin with double hyphen (--)
Use the custom property with the var() function
https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties
:root { Element {
--main-color: red; color: var(--main-color);
} }
CSS Layout
In the beginning there was very little control over layout
Most pages content was just displayed in the order of the HTML
HTML only had some attributes that applied styling
For more complex layouts nested table elements were used
With the creation of CSS, the separation of HTML and style was
possible
The CSS Zen Garden project showed the power of CSS
CSS Layout
CSS Page Layout Techniques
Normal Flow
Display Property
Flexbox
Grid
Floats
Positioning
Table Layout
Multiple-column layout
https://developer.mozilla.org/en-
US/docs/Learn/CSS/CSS_layout/Introduction
CSS Layout
Normal Document Flow
HTML is displayed in exact order of the document
Block direction runs according to language
Display Property
Main property to do page layout in CSS
Changes way an element displays
Elements have a default value, mostly block or inline
Can be used to change the default presentation like have a block act
like an inline or an inline act as block
Two main modern display layout values are flexbox and grid
CSS Flexbox
Flexible Box Layout CSS module
Designed for one-dimensional layout, single axis, rows or columns
Set display: flex on the parent container and all the direct children
elements become flex items
By default, it will layout the flex items horizontally next to each other and
the same height with no wrapping
Other properties to adjust this behavior
There are also properties to control how how the items grow or shrink and
the order they will display
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
CSS Grid
CSS Grid Layout Module
Designed for two-dimensional layout , multi-axis, rows and columns
Set display: grid on the parent container and all the direct children
elements become grid items
By default, it doesn’t look any different, unlike flexbox, you get a one
column grid
Row and column tracks on the parent are created with the grid-
template-rows and grid-template-columns properties
They can be defined with normal units or with the fractional unit fr
Gaps between tracks created with column-gap and row-gap properties
Gaps need to be length or percentage, not fr
CSS Grid
There is a repeat function that will allow you to define repetitive tracks in
your grid-template rows or columns
Tracks you create are the explicit grid and there is also implicit grid
Implicit tracks are created with auto size by default, but they can also
have default sizes with grid-auto-rows or grid-auto-columns
There is s minmax function that you can use to set the min and max size of
a track
Grid item placement can be controlled and allow for placement at any
grid tracks with the grid-column and grid-row properties
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Grids
https://learncssgrid.com/
https://css-tricks.com/snippets/css/complete-guide-grid/
CSS Floats
Removes an element from the normal document flow and moves it to the left
or right
Causes the following elements to float or wrap around it
The clear property is used to stop a following element from floating or
wrapping around the element
Originally created to float an image in some text but was used to float
anything
These techniques were used to create multi-column layouts in days before
flexbox or grid
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Floats
https://developer.mozilla.org/en-
US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods
CSS Positioning
We talked about this last week
Uses the position property with one of the following values
Static – default normal flow
Relative – puts the element in normal flow but allows you to move it after
Absolute – takes element out of the flow and positions it to the first parent
that has a positioning context
Fixed – positions element based on browser viewport
Sticky – newer combination of relative and fixed
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning
CSS Table Layout
CSS properties that define the way tables lay out in a page
These properties can be applied to other elements that are not
tables to get them to lay out like tables
Now this should be considered a legacy method and not used
unless you can not use flexbox or grid
CSS Multi-column
Provides a way to lay out content in columns like a newspaper
Not as useful for web content because you would have to scroll up
and down
Can be useful for things like long lists
Make a block element into multiple columns with either the column-
count or column-width properties
There is also a column-gap property to add space between
columns
https://developer.mozilla.org/en-
US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout
Responsive Design
Basic HTML is responsive by default
Text reflows depending on the screen size
For example, a paragraph element (block element) will take the full
width of its container and the text will reflow to fit.
Where this becomes an issue is when you are tying to go beyond basic
HTML flow and do a stylized layout
Historically pages would use either a fluid or fixed layout
Fluid layout allows elements to fill their container or have set widths based on
percentages
Fixed layouts would have elements set to specific pixel dimensions
Often pages would be design to look good on a specific screen size
For a long time that was a 960px width because it fit on 1024x768 monitors
Responsive Design
The next era of layouts came as phones started being able to show
web pages
Basic feature phones where very limited so people started designing
separate mobile websites usually on a different domain
As phones got more powerful and could display a full featured web
page (starting really with iPhone) this became limiting
Along came the concept of responsive design in 2010
https://developer.mozilla.org/en-
US/docs/Learn/CSS/CSS_layout/Responsive_Design
Responsive Design
Was made primarily of three techniques together
Fluid Grids/layouts
Fluid Images
Setting the max-width property to 100%
Media Queries
Ability to load different CSS based on media rules like screen size
Media Queries Level 3 specification in 2009
Need to add the viewport meta tag to tell mobile browser to not
scale the pages to fix 980px and just make the viewport the device
width
Media Queries
They can be used to target rulesets to specific screen sizes, system settings,
or media types like print
Two ways to use them
@media rule in a stylesheet that surrounds the rulesets that you want to apply to
that media condition
@media type and (feature)
Using the media attribute on a link tag to only load a stylesheet if that media
condition applies
<link rel="stylesheet" href="specific.css" media="type and (feature)">
https://css-tricks.com/a-complete-guide-to-css-media-queries/
Responsive Images
Basic idea here is images will never be bigger than their container and
are allowed to scale down
At a most basic level you set images max width with one of the
following properties
max-width: 100%;
max-inline-size: 100%; and block-size: auto;
You can deliver different size images based on media conditions with
images and the srcset and sizes attributes
You can do art direction and serve different images altogether with the
picture element and source elements
https://developer.mozilla.org/en-
US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images
CSS Transitions
Transitions are a way to control the speed of a CSS property change
You can set things like duration and delay of property changes
Uses the transition shorthand property or the individual properties
of transition-property, transition-duration, transition-
timing-function, transition-delay
The transitions will apply when an elements CSS state changes,
typically things like hover or a class is added or removed for
example
Not all properties can be transitioned, only animatable ones
CSS Transforms are common since they are hardware excellerated
https://developer.mozilla.org/en-
US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions
CSS Transforms
Transforms are used to change the shape and position of elements
Transforms do not affect the normal document flow
Transforms include rotation, skewing, scaling, and translation
Can be in 3D space in addition to the normal 2D plane
Only elements with display: block can be transformed
Two main transform properties
transform
Space separated list of transforms to apply
transform-origin
Position of the origin for the transform, by default it is the center of the
element
CSS Transforms
The transforms are a series of functions
Scale
Scales an element along one or more of its axis's
rotate
Rotates an element around its origin
Translate
Moves an element along one or more of its axis’s without affecting the
document flow
Skew
https://developer.mozilla.org/en-
US/docs/Web/CSS/CSS_Transforms/Using_CSS_transforms
CSS Animations
CSS Animations allow you to animate changes to CSS styles from one
set of rules to another
Can be more complex than a simple transition, instead of going from
one point to another there can be in-between keyframes
Same animatable properties as transitions
Transitions trigger on simple state changes, there is much more control
over duration, iteration, playback control with animations
There is a shorthand property animation, but you can use all the
individual properties instead
The @keyframes at rule defines the steps of the animation sequence
https://developer.mozilla.org/en-
US/docs/Web/CSS/CSS_Animations/Using_CSS_animations
JavaScript Introduction
JavaScript is the behavioral layer of our web pages. HTML is structural, CSS is
presentational
Scripting language that enables dynamic content on the page
Can access all the elements, attributes and text on a web page using the DOM
(Document Object Model)
Can test for browsers features and capabilities, progressive enhancement
Modify elements and CSS properties to show, hide, and change element
appearance
Makes AJAX interactions possible and background content updates
Historically support between different browsers has sometimes been mixed.
Some browser implementations support some features and some use different
names or syntax for a given feature.
JavaScript Introduction
Not Related to Java Programming Language
Originally named LiveScript and created by Brendan Eich at Netscape
in 1995. Later renamed JavaScript for marketing reasons because of
popularity of Java Language at the time.
Standardized by ECMA technically ECMAScript
Almost universally supported legacy version is ECMAScript 5 – JS 1.8.5
ES6+ are the newer modern versions, use it now in most modern browsers or
with a complier like babel
Newest version is 13 edition, June 2022 or ECMAScript 2022 language
Specification
Lightweight Object-oriented scripting language
Procedural, object-oriented (prototype-based), and functional style
Interpreted - Doesn't need to be compiled to machine code
Dynamic Loosely Typed Language - Don't need to declare variable types
JavaScript Introduction
JavaScript is the language and basic built-in objects and functions you can use.
First and mostly existed as a browser language but is now being used in many
other environments like NodeJS
The environment that the JavaScript is being executed in will provide some APIs
The browser engine gives you many such as DOM, Geolocation, Canvas, Audio,
Video, and many more
3rd party APIs and code can be added to your pages to provide other
capabilities like the Google Maps API for example. Let’s try one.
https://www.w3schools.com/js/tryit.asp?filename=tryjs_api_geo_coordinates
JavaScript Introduction
Mozilla JavaScript Guide
https://developer.mozilla.org/en-US/docs/Web/JavaScript
Wikipedia JavaScript Entry
http://en.wikipedia.org/wiki/JavaScript
https://en.wikipedia.org/wiki/ECMAScript
JavaScript and Basic Programming Introduction Reading. Read over chap 1-2:
http://eloquentjavascript.net/
ECMAScript 13th edition – 2022 Specification
ECMAScript 6th edition – 2015 Specification
ECMAScript 5.1 edition – 2011 Specification
Adding JavaScript to a page
Embedded/Internal Scripts
Use script tags <script> JS Here </script>
External Scripts
Use script tag with src attribute <script src="myscript.js"></script>
Script tag must be empty inside
Can be placed anywhere on the page, blocks when executing
Most commonly in head section or at the bottom of the body before the closing body tag
Type attribute was required in <= html4 but not html5
<script type="text/javascript"></script>
There are async and defer attributes in html5, async="async" & defer="defer”
Async downloads as page is parsing then blocks to execute
Defer downloads as page is parsing then executes when page finishes parsing
When either is not present (default), executes immediately and blocks then finishes parsing page
http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html
JavaScript Language
Values and Variables
Objects
Statements
Blocks
Functions
Operators
Comparison
Conditional Statements
Looping
JavaScript Basics
JavaScript is case-sensitive “foo” not equal “Foo”
Made up of statements which should end with a semicolon.
Contains reserved words you can not use. Search for a list of
JavaScript reserved words for details.
https://developer.mozilla.org/en-
US/docs/JavaScript/Reference/Reserved_Words
Comments can be single or multi line
Single Line – two slashes // This is a comment
Multi Line – similar to css /* This is a comment */
JavaScript Variables
Variables hold values or objects
Declared with var keyword (pre ES6) var foo;
Set value with single = sign var foo = 5;
Names are case sensitive
Names must begin with a letter or the underscore
Can be a set of very basic data types: numbers, bigints, strings,
booleans, objects, functions, symbols, undefined, and null values
No special characters in name (! . , / \ + * =)
Has functional scope – not block scope (ES5 with var)
If a variable is declared in a function without var keyword it's global
JavaScript Variables
ES6 + Introduces new keywords to declare variables and constants
These new keywords introduced block scoping
let keyword
let declares a block scoped variable
const keyword
const declares a block scoped constant
Once a value is assigned it can not be changed
Object properties can be changed though, we will see an example later
https://dev.to/sarah_chima/var-let-and-const--whats-the-difference-
69e
JavaScript Values
Consist of primitive values and objects
undefined – used for unintentionally missing value
null – used typically for intentionally missing values
booleans – true/false, used for logical operations
numbers – (25, 3.1415) all numbers but limited precision as you get further from 0 and used for math
bigints – (uncommon, new) large integers for more precision and math on big numbers 232131231233123123n
strings – text and immutable, all possible strings exist as values
symbols - (uncommon)
functions – used to refer to code and execute that code (functions are objects)
objects – group related data and code
typeof operator will tell you the type of value a variable points to
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
https://developer.mozilla.org/en-US/docs/Glossary/Primitive
JavaScript Array
Array – grouping/collection of objects in a single variable name
Arrays are objects
Not Associative arrays so you must use integer indexes
Arrays are defined with either the new array constructor or array literal
new Array() or [ ]
Zero-indexed so first element is: arrayname[0]
Each location in an array can hold any value
Arrays have methods and properties to manipulate it, see reference
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array
JavaScript Objects
Object - All items except primitive data types in JavaScript are objects
including functions
Objects are basically a custom data structure
No class system in JavaScript like in other programming languages. Uses
Prototypes instead. Has a system of Prototype Inheritance. Class
keyword added in ES6.
The browser is the window object the html page is the document object
Objects are composed of properties and methods
Properties are basically variables
Methods are basically functions
Access an objects property – obj.propertyName
or obj["propertyName"]
Execute an object method – obj.methodName()
JavaScript Objects
Created by a function with new keyword
var obj = new Object();
Created with an object literal
var obj = {};
var obj = { key: value, key2: value2 };
Key needs to be a string with no spaces, can not start with number or special character
var obj = { color: "red", quantity: 5, instock: true };
Access or set properties with dot notation
obj.color = "blue"; sets color of obj to blue
obj.quantity; would be equal to 5
Can also set or execute methods this way obj.run()
You can also access properties with the array like syntax of
obj["color"]
Useful when you need the property value to come from another variable
JavaScript Objects
JavaScript Object Literal format is most common
An object literal is a comma separated list of name value pairs
wrapped in curly braces.
var myObject = {
stringProp: 'some string',
numProp: 2,
booleanProp: false
};
Value can be any JavaScript Datatype including a function or other
object.
JavaScript Objects
Object Reference Documentation
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Object
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects
Standard Objects
JavaScript has many standard built-in objects
Some of these objects provide methods to manipulate basic data
like strings, numbers, dates, and more or act as wrappers around
primitives
Some important basic ones to study are Array, String, Number, Math,
Date
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects
JavaScript Statements
Statements are commands to the browser that are
executed in order
Should end with a semicolon but not required. JS has ASI
ASI - https://stackoverflow.com/questions/2846283/what-are-
the-rules-for-javascripts-automatic-semicolon-insertion-asi
May span multiple lines if written carefully
Multiple statements may be on the same line if separated by
a semicolon.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Statements
JavaScript Blocks
Statements can be grouped together in blocks with the curly
brackets { }
Usually, blocks are used when defining functions or using
conditionals or loops
JavaScript does not use block scope like most programming
languages. It has function scope. This can change in ES6 with the
new variable keywords, but you need to understand what version
and syntax you’re using and how it will behave.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Statements/block
JavaScript Basic Math Operators
Addition + (plus operator is also used to concatenate strings)
Subtraction -
Multiplication *
Division /
Modulus (division remainder) %
Exponent **
Increment ++ and Decrement --
Add to self and reassign +=
var car = 5; car += 2; car is now 7
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Math
JavaScript Functions
Named blocks of code that can be called and executed by events or
other code, may take parameters
Functions are objects in JavaScript
function funcname (var1, var2, …) {
code block (may make use of parameters)
}
The return statement will stop executing the function and return the
value
function addnum(n1, n2) {
return n1 + n2;
}
JavaScript Functions
Can be created with Function Declarations or Function Expressions
Function Declarations
function myFunction() {
statements;
}
Can be defined after being used. Defined in initial parse phase.
Function Expression
var myFunction = function(){
statements;
};
Must be defined before being used. Little clearer that the var myFunction
holds a function. Defined during execution.
JavaScript Functions
There is a third way to declare a function
ES6 Introduced arrow function expressions
Don’t introduce their own binding to the this keyword
If the arrow function is one line it will have an implicit return
(a, b) => {
return a + b;
}
(a, b) => a + b;
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
JavaScript Functions
JavaScript has many built in functions and objects as part of the language and
specification.
The functions available will vary depending on the execution environment.
Useful basic built-in functions:
alert()
confirm()
prompt()
console.log()
Number() vs parseInt() or parseFloat()
Math and Date objects
Many more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects
JavaScript Comparison Operators
Comparisons are used to compare the value of two objects and return true or false
Comparison Operators
== Is equal to
!= Is not equal to
=== Is identical to (equal to and same data type)
!== Is not identical to
> Is greater than
>= Is greater than or equal to
< Is less than
<= Is less than or equal to
alert( 5 > 1 ); // Will alert “true”
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Guide/Expressions_and_Operators#comparison_operators
JavaScript Conditional Statements
Basic conditional statement is the if/else/else if
Used to branch code on conditions
Else and else if are completely optional
if ( condition ) {
run this block
} else if (condition) {
run this block
} else {
run this block
}
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#conditional_
statements
JavaScript Basic Loops
for – loops through a block a specific # of times
while – loops through a block while condition true
do...while – loops through block once then repeats as long as a condition is true
for...in – loops through all properties of an object, be careful with this one can be error
prone. Do not use to loop through an array.
for...of – loops over an iterable object
For Loop Syntax
for (initialize the variable; test the condition; alter the value;){
code to loop here
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code
JavaScript Functions (Revisited)
Named blocks of code that can be called and executed by events or
other code, may take parameters
Functions are objects in JavaScript
function funcname (var1, var2, …) {
code block (may make use of parameters)
}
The return statement will stop executing the function and return the
value
function addnum(n1, n2) {
return n1 + n2;
console.log(“This statement will not print”);
}
JavaScript Functions Examples
Console.log(myTotal)
113
NOTES:
• Parameters are
defined for a function
and arguments are
passed to a function
JavaScript Functions (Revisited)
You can watch the following videos for more information about
JavaScript functions:
https://youtu.be/FOD408a0EzU?si=Fw7DvND5oZGn1Cwh
This video is approximately 10 minute. Will not be shown in class but
you are responsible for its content.
JavaScript OOP Patterns
Patterns to implement Object Oriented Programming in JavaScript
We will be looking at a few basic ones:
Object Literal
Constructor Function (Constructor Pattern)
Constructor Function with Prototype (Constructor Pattern)
Function that returns an object (Factory Pattern)
ES6 Classes
https://leoasis.github.io/posts/2013/01/24/javascript-object-
creation-patterns/
Public, Private, Privileged
These are ways we can have private and public members and methods for
objects when we model them with the Constructor pattern.
Functions and variables assigned in a constructor with the this keyword
will be publicly visible. Functions and variables assigned normally will be
private.
Be careful, the this keyword can get bound to the window object so it is
common to see a var that = this; line in the object to bind that to the
proper this value.
We will do an example to show these three ideas.
http://crockford.com/javascript/private.html
http://robertnyman.com/2008/10/14/javascript-how-to-get-private-
privileged-public-and-static-members-properties-and-methods/
ES6+
The 6 edition of the ECMAScript-262 standard for JavaScript
Also known as ECMAScript 2015
Was finalized and published in June 2015
This added significant new syntax and features
Native support in all modern browsers currently, for most features
Can use a tool like Babel to transpile to ES5 for compatibility
New additions are published yearly. Browser support can lag behind
slightly.
https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_-
_ECMAScript_2015
https://kangax.github.io/compat-table/es6/
ES6 Features
http://es6-features.org/
ES6 adds some new syntax and features. Some of the bigger changes are:
Classes
Block-Scoped Constructs let and const
Arrow Functions
Default Parameters
Rest and Spread Parameters
Destructuring Assignment
Template Strings
Multi-line String
Maps & Sets
Modules
http://kangax.github.io/compat-table/es6/
Classes
ES6 added a class syntax similar to other languages.
Just syntactic sugar, still prototypal under the hood.
Constructor is used to setup parameters and set properties.
https://javascript.info/classes
https://developer.mozilla.org/en-
US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript
class Song {
constructor(title, artist, duration) {
this.title = title;
this.artist = artist;
this.duration = duration;
this.isPlaying = false;
}
start() {
this.isPlaying = true;
}
}
Classes
Classes can have getter and setter properties/methods
These allow you to add methods that handle class properties when you use dot notation to get or
set their value
https://javascript.info/property-accessors
class Song { let s = new Song(‘hello’);
constructor(title) {
this._title = title;
} s.title; //returns ‘hello’
get title() {
return this._title; s.title = ‘goodbye’;
}
set title(t) { s.title; //now returns ‘new title:
this._title = “new title: ” + t;
} goodbye”
}
Classes
Classes can have inheritance
Uses the extends keyword to define a “subclass”
Still uses prototype inheritance in the background
https://javascript.info/class-inheritance
class RockSong extends Song {
constructor(title, artist, duration, type) {
super(title, artist, duration);
this.type = type;
}
logType(){
console.log(this.type);
}
}
Classes
Public & static class fields
Newer features, may not be supported in all runtimes. (ES2019)
Allows you to define public class fields outside the constructor.
Private class fields would be prefixed with #. Expanded use of that or introducing a private keyword is in discussions.
Also allows for a static keyword for static fields that are shared on the class
Class ClassWithPublicAndStaticFields {
static staticProperty = ‘aValue’;
instatceProperty = ‘aValue’
#privateProp = ‘aValue’;
static staticMethod() {
return ‘static method statements’;
}
publicMethod(){
return ‘public method statement’;
}
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static
https://www.sitepoint.com/javascript-private-class-fields/
Block Scope
Remember that when using the var keyword to declare a variable
there is no block scope, only functional scope.
ES6 adds two new keywords that declare block scoped constructs
let
const
let is similar to var but has block scope
let is the new var
const declares an immutable variable that also has block scope.
Once the value is assigned it is fixed and can’t be changed. You
can change the value of object properties or array elements
though.
Arrow Functions
This is a new syntax to declare a function
Using an arrow function fixes the problems associated with the this
keyword in some cases. The this keyword will have the same value
as in the context of the enclosing function. It fixes the problem when
creating closures and makes the that = this less necessary. Not
to be used in all cases, see MDN link.
If the function executes a single statement, it will implicitly return the
result of that statement.
Old Style New Style
function add (a, b) { const add = (a, b) => a + b;
return a + b
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Default Parameters
Default parameters are parameters to a function that are given
some default values in the function declaration.
The value can be changed when calling the function
const add = (a = 5, b = 6) => {
return a + b;
}
function add(a = 5, b = 6) {
return a + b;
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
Rest Parameter
You can use the rest prefix of … to extract the rest of the args from a
function.
This lets you accept unlimited number of parameters and process them
dynamically.
They come in as an array and only has the arguments that were not
provided explicitly.
function add(a, b, ...more) {
// more variable in this block is an array of as many
params that were passed
}
add(5, 6, 8, 2, 5, 6);
Inside the add function more is. [8, 2, 5, 6]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
Spread Operator
Similar to the rest parameter in look but functions differently
It spreads out the values of an array or iterable to separate elements
Uses the … before the variable name
var params = [“hello”, true, 7];
var other = [1, 2, ...params ]; // results are [1, 2, “hello”, true, 7]
var val = [1, 2];
function add(a, b) { return a + b }
add(...val) // outputs 3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Destructuring
Destructuring allows you to extract values from arrays and object
Uses the array brackets or object curly brackets
let arr = [5, 8, 2, 5];
let [x, y, z, w] = arr;
// x is 5, y is 8, z is 2, w is 5
var o = { p: 42, q: true };
var { p, q } = o;
// p is 42 and q is true
Can rename obj properties to new variable names
var {p: foo, q: bar} = o;
//now foo is 42 and bar is true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Template and Multi-line String
Use the back tick (`) to define and wrap the string.
This is for both template strings and multi-line strings.
With template strings you can then evaluate variables in the string
with ${}
Multi-Line String
var text = `This is a mult line string that
continues on to the next line.`;
Template String
var name = ‘anita';
var greeting = `Hello ${name}!`;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Maps and Sets
Map
Holds key-value pairs similar to an object but keeps track of insertion
order. Maps are iterable. Keys don’t have to be strings but can be any
object.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Map
Set
Collections of unique values of any data type. Sets are iterable and also
keep track of insertion order. A value in a set can only occur once.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Set
https://javascript.info/map-set
HTML Forms
Forms are used to collect and send data back to a server or resource that
can process the data
Forms CAN NOT be nested inside other forms
Forms collect data with form controls
Really two parts
form element and form controls in the HTML page that the user interacts with
Some kind of server-side resource that the form will transmit the data to
You can use form controls outside a form but they will not transmit any data
without using some type of JavaScript to read and submit the data from
them
If you send the data using JavaScript, you will want to stop the default form
processing with the submit events preventDefault method
Form controls provide us a way to get data from the user
HTML Forms
Form element contains all form controls
<form></form>
Has two primary attributes you need
action & method
<form action="URLToScript" method="post"></form>
Action attribute
The URI of a program that processes the form information.
Method attribute
The HTTP method that the browser uses to submit the form.
Form Method
The HTTP method that the browser uses to submit the form. Possible values are:
POST
Corresponds to the HTTP POST method
Form data is included in the body of the HTTP Request and sent to the server.
Most often used
No character or size limit to data
GET
Default if no method is specified
Corresponds to the HTTP GET method
Form data is appended to the action attribute URI with a '?' as separator, and the resulting URI is sent to the server.
http://server.com/script.php?name=Bob&city=chicago
Only use this method if the form has no side-effects and contains only ASCII characters.
URL length is limited and varies by browser & server
Neither method does any encryption of the data. That is the responsibility of TLS (SSL) during the
connection.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
Form Controls
Form controls are used to collect input data from the user and submit them to some
resource that processes that data.
In basic HTML forms, the form controls need to be nested inside the <form></form> tags.
Form controls can be used outside a <form> tag in an HTML page but there is no way for
it to submit data without using JavaScript to read and submit the data.
All form controls use a name attribute, or the data will not be submitted when using the
form tag
Form controls use a type attribute to set the type of control (there are a couple
exceptions).
You should always use label elements for accessibility
https://developer.mozilla.org/en-US/docs/Learn/Forms/Basic_native_form_controls
https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_submit
STOP HERE AND COMPLETE A FULL FORM EXAMPLE FOR DIFFERENT DATA TYPES
Introduction to the DOM
• WILL COMPLETE ABOUT ½ OF THE SLIDES.
• DOM DEMO NEXT WEEK.
• ONLY WHAT IS COVERED IN CLASS WILL BE ON THE
NEXT QUIZ.
The DOM
Document Object Model (DOM)
Object representation of a HTML or XML Document in memory
All elements are represented by objects
DOM is an API that can be used in many languages
JavaScript uses DOM scripting to modify the elements on a page
DOM is a collection of nodes in a tree
Also provides standard methods to traverse the DOM, access
elements and modify elements
https://developer.mozilla.org/en-
US/docs/Web/API/Document_Object_Model/Introduction
JavaScript DOM
Accessing the DOM elements
Use methods of the document object
Most common by id
let a = document.getElementById("elementid");
Can also access by class, tag, selector
Use the Element.getAttribute("src"); method to get an
attribute's value from an element. Use the setAttribute to set or
change one.
Many other methods and properties to access, transverse, and
manipulate DOM objects.
https://developer.mozilla.org/en-
US/docs/Web/API/Document_Object_Model
Click on “Introduction to the DOM” Examples are near the bottom
DOM Selection Basics
By Id – always will return one DOM element since id needs to be unique on the page.
let element = document.getElementById(‘someId’);
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
By Class Name – returns an HTMLCollection
let elements = document.getElementsByClassName(‘classnames’);
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
By Tag Name – returns an HTMLCollection
let elements = document.getElementsByTagName(‘tagname’);
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
By Selector – returns one element or a NodeList of element objects, uses CSS style selectors
let element = document.querySelector(‘css selector string’);
let elementList = document.querySelectorAll(‘css selector string’);
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
JavaScript Event Handling
Three Methods – 3rd method is the most preferred way
1. As attribute on HTML element
2. As a method attached to a DOM object
3. Using the addEventListener method of an object
JavaScript Event Handling
Method 1
As attribute on HTML element
Not suggested, mixes JavaScript and HTML structure in the HTML
markup.
Uses the attribute that pertains to the particular event. Usually in the
form of on + something. Click event is onclick for example.
JavaScript code is embedded in the event attribute’s value.
<div onclick="alert('I was clicked')">click me</div>
JavaScript Event Handling
Method 2
As a method attached to a DOM object event property
Not suggested, while it separates the event handler logic from the HTML markup
you still have limitations.
Can only apply one event handler to an element using this method.
JavaScript function is assigned to the event name property on the element. Click is
onclick for example.
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers
<div id="aButton">Click Me</div>
document.getElementById('aButton').onclick = function(){
//code in this block
};
JavaScript Event Handling-Method 3
Using the add event listener method of an object
This is the preferred modern standards compliant method. This is what I want to see
unless you have good reason to use the other two and can explain why.
This allows you to bind multiple handlers on the same element to listen for the same
event.
Event types are without the word “on” before them. Click is click.
https://developer.mozilla.org/en-US/docs/Web/Events
element.addEventListener("click", myFunction, false);
Make sure you pass the function object, not execute the function. Notice no
parenthesis. Or declare an anonymous inline function.
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
EXAMPLE NEAR THE BOTTOM
STOP HERE-WEEK 7. JUMP TO ASSIGNMENTS AT THE END.
Capture/Bubble Event Phases
Event handlers can be registered in either the bubbling (default) or capturing
phases of the event cycle.
This determines how nested elements with the same event handlers will
process them.
The capture phase starts at the highest element in the chain down through
the ancestors to the target element
The bubble phase starts at the target element and then goes up through the
chain
See demo and links
https://javascript.info/bubbling-and-capturing
https://developer.mozilla.org/en-
US/docs/Learn/JavaScript/Building_blocks/Events
https://blog.logrocket.com/deep-dive-into-event-bubbling-and-capturing/
Waiting for the DOM to be ready
How do you prevent your JS from running before the page is ready to be manipulated?
You could add and an event handler to the widow’s load event
This will fire the event handler at the end of the document loading process. All objects in the document
are in DOM and all images, scripts, and other assets are also loaded.
Sometimes this will take longer than you really need. Most of the time you really just want the DOM to
be ready to be manipulated.
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
Better option is often using the DOMContentLoaded event on the window or document object.
This event fires when the HTML document has been fully loaded and parsed. It does not wait for other
assets like images and stylesheets.
This event is often what you want vs listening for the full load event.
https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event
https://gist.github.com/jsonberry/0d71007ea188785e1a3d13d2e30d58a5
Load vs DOMContentLoaded
Load event
window.addEventListener('load', function (evt) {
console.log('page is fully loaded');
});
DOMContentLoaded event
document.addEventListener('DOMContentLoaded', function (evt) {
console.log('DOM fully loaded and parsed');
});
See demo
DOM Element Manipulation
DOM elements have a property, innerHTML, that sets or gets the HTML syntax that describes
all the element’s children.
DOM elements also have an innerText property that can be used if the inner content is
only text with no HTML syntax. HTML will not be parsed and inserted as plain text.
let content = element.innerHTML;
element.innerHTML = ‘<p>New HTML</p>’;
let content = element.innerText;
element.innerText = ‘this is some text’;
innerHTML can introduce security concerns so you need to use it carefully.
There is also a textContent property that is very similar to innerText. It differs in that it
textContent will also get hidden text text content like a <script> tag not just visible text.
https://developer.mozilla.org/en-
US/docs/Web/API/Node/textContent#differences_from_innertext
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
DOM Element Manipulation
Getting values from form fields.
Most basic is the input element. This could be of type text, button,
checkbox, radio, and others that use the HTML <input> element form
control.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
https://developer.mozilla.org/en-
US/docs/Web/HTML/Element/input#Form_<input>_types
Many properties to interact with the control. Very important one that
applies to all types of input controls is value. Gets or Sets the value
element.value = '5';
let result = element.value;
All values are get or set as a string from a form control. You must do any
type conversions.
DOM Element Manipulation
Other popular form controls include
Select lists
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement
See properties selectedIndex, selectedOptions, value, and others
Text Areas
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement
value property to get/set value same as input
Helper methods you should looks into.
Number() - Object
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Number
Other built in global functions and objects
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
Be very careful with the parseInt() function’s behavior as demoed in class and the NaN type.
DOM Element Manipulation
Elements are the basic object everything descends from. Review this link for basic
properties and methods that apply to all elements.
https://developer.mozilla.org/en-US/docs/Web/API/Element
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement
To properly create, move, delete, or modify elements you need to use properties
or methods on the elements.
Changing Inline CSS Styles
document.getElementById('anId').style.backgroundColor = '#000000';
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
CSS properties on style object usually use a camel case version of the name. Look
it up if you can not figure it out.
DOM Element Manipulation
Methods used to create and insert an element
document.createElement()
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
document.createTextNode()
https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode
node.appendChild()
https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
node.insertBefore()
https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
node.removeChild()
https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild
node.replaceChild()
https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild
DOM Element Manipulation
For example, to insert a new h3 in the body of an HTML page
let head3 = document.createElement(‘h3’);
let headtext = document.createTextNode(‘This is my H3 headline’);
head3.appendChild(headtext);
let b = document.getElementsByTagName(‘body’);
b[0].appendChild(head3);
EXERCISE 1
Use the getElementById method to find the <p> element, and
change its text to "Hello".
<p id=“demo”></p>
<script>
document.getElementById("demo").innerHTML = “Hello”;
</script>
EXERCISE 2
Use the getElementsByTagName method to find the first <p> element,
and change its text to "Hello".
<p id=“demo”></p>
<script>
document.getElementsByTagName("p")[0].innerHTML = “Hello”;
</script>
EXERCISE 3
Change the text of the first element that has the class name “Test”.
<p class="test"></p>
<p class="test"></p>
<script>
document.getElementsByClassName("test")[0].innerHTML = “Hello”;
</script>
EXERCISE 4
Change the text color of the <p> element to "red".
<p id=“demo”></p>
<script>
document.getElementById("demo").style.color = “red”;
</script>
EXERCISE 5
Use the eventListener to assign an onclick event to the <button> element.
<button id="demo">Click me1</button>
<script>
document.getElementById("demo").addEventListener(“click”, myFunction);
</script>
JSON
JSON is JavaScript Object Notation
Lightweight data exchange format that is easily for humans to read or write
Plain text format that is language independent but was based on a subset of
JavaScript language syntax
Usable in most languages so it is an ideal data-interchange format
JSON is built on two universal data structures that map to almost all programming
languages
Collection of name/value pairs
Ordered list of values
Standardized by ECMA International as ECMA-404
https://www.ecma-international.org/publications-and-standards/standards/ecma-404/
JSON
Collection of name/value pairs
Realized in languages as object, record, struct, dictionary, hash table,
keyed list, or associative array
In JSON and JavaScript this is an Object
Unordered set of name/value pairs
Ordered list of values
Realized in languages as array, vector, list, or sequence
In JSON and JavaScript this is an Array
Ordered collection of values
https://www.json.org/json-en.html
SHOW VIDEO
JSON
Property names must be double quoted
String values must be double quoted
Trailing commas are forbidden
Numbers can not have leading zeros
If a number has a decimal point, it must be
followed by at least one digit
NaN and Infinity are not supported
Values can be:
object
array
string
number
boolean value of true or false
null
JSON Example that could represent a person https://en.wikipedia.org/wiki/JSON
JSON
JavaScript provides a JSON object which contains methods for parsing JSON
text to JavaScript objects and converting JavaScript objects to JSON text.
These methods are available on the JSON object
JSON.parse(text)
The parse method will convert the JSON formatted text string that is passed to it to
the corresponding JavaScript objects
JSON.stringify(value)
The stringify method will convert JavaScript objects to the corresponding JSON
formatted text
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/JSON
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON
EXERCISE JS 1
var obj = { color: "red", quantity: 5, instock: true };
Command to change obj color to green
obj.color = “green";
EXERCISE JS 2
let x = 200%3;
x += 13
What is the value of x?
x is 15
200 divided by 3 is 66 with a reminder of 2
Add 13 to 2 and it is 15
EXERCISE JS 3
let x = 10;
if (x > 10) {
x=x-7;
console.log(x);
} else if (x > 5) {
console.log(x+3);
}
What is output to the log? x is 13
EXERCISE JS 4
total = 0;
for(let i=0; i<6; i++){
total = total + i;
}
console.log(total);
What is the output? 15
EXERCISE JS 5
Given the following JavaScript array:
myArray = [‘red’, ‘blue’, ‘green’, ‘black’, ‘gray’, ‘orange’];
What is the value of myArray[6]?
Index out of range error
AJAX
AJAX – Asynchronous JavaScript And XML
AJAX is not a programming or markup language it is a combination
of technologies that were already in use.
HTML (or XHTML) and CSS
DOM
XML or JSON
XMLHttpRequest Object
JavaScript
The term was coined by Jesse James Garrett in 2005 when he
described the use of these technologies together in an article
named AJAX: A New Approach to Web Applications
AJAX
Brief History of AJAX
It all starts with Microsoft and Internet Explorer
In 1996 IE introduced the iframe tag which allowed for loading of content
asynchronously.
In 1998 the Outlook Web Access team came up with the concepts and created
an ActiveX control XMLHTTP which was released in IE 5 in March 1999
Mozilla developed an interface that modeled the XMLHTTP object as closely as
possible and created a JavaScript object called XMLHttpRequest for their
Gecko engine.
First available in v0.6 in December 2000 but not fully functional until V1.0 in June 2002
XMLHttpRequest became a de facto standard in other major web browsers
AJAX
W3C published a draft of the XMLHttpRequest object specification
in April 2006.
Microsoft adopted the XMLHttpRequest object and added it to IE7
in October 2006.
This allowed for using the object without platform specific code
The XMLHttpRequest specification is now a whatwg living standard
The newer Fetch API specification has been introduced to provide
the same functionality with a simplified promise-based API
AJAX
Requests are sent to the server and responses are received
asynchronously in the background and processed by JavaScript
without a full page load.
This allows for smaller incremental updates to the UI
The application/webpage will feel faster and more responsive to the
user's interactions
The X in AJAX stands for XML but it is not required anymore
JSON is the preferred option now since it has advantages.
JSON is part of JavaScript and more lightweight
There can be various response types including plain text and html
XML responses require using XLST to process
AJAX Basic Steps
Event occurs in page that triggers AJAX request (click or something)
XMLHttpRequest object is created and configured
The XMLHttpRequest object sends an asynchronous request to the
server
Server processes the request in back-end code
Server sends a response back to the XMLHttpRequest object including
the results as response text. Check readyState and status to see if
success.
The XMLHttpRequest object uses the configured callback function to
run and process the results if successful, or proper error response if not
JavaScript in the callback function updates the HTML, DOM, and CSS of
the page as needed
AJAX Flow
AJAX
XMLHttpRequest (XHR) Important Properties and Methods if
xhr === XMLHttpRequest
http://en.wikipedia.org/wiki/XMLHttpRe
quest xhr.onreadystatechange
https://developer.mozilla.org/en- xhr.readyState
US/docs/Web/API/XMLHttpRequest
xhr.status
https://developer.mozilla.org/en-
US/docs/Web/API/XMLHttpRequest/Usin xhr.responseText
g_XMLHttpRequest
xhr.open()
All modern browsers and IE 7 + support xhr.send();
the native XMLHttpRequest object.
Ready State is an unsigned int
For IE < 7 support you would need to use
the active x version. (not a problem https://developer.mozilla.org/en-
anymore, if interested just for information US/docs/Web/API/XMLHttpRequest/rea
there are resources online that talk about dyState
this)
Can use constant as comparison
instead of the number.
XMLHttpRequest.DONE same as 4
AJAX Same-Origin Policy
Script code must come from same server, domain, subdomain,
protocol, port as the ajax call
http://en.wikipedia.org/wiki/Same_origin_policy
CORS will allow for cross-origin requests
https://enable-cors.org/
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Basic CORS support can be achieved as long as the cross-origin
resource providing the data sets the proper header
Access-Control-Allow-Origin: *
AJAX Basic Example
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function(){
if (myRequest.readyState === 4) {
if (myRequest.status === 200)
var myArray = JSON.parse(myRequest.responseText);
parseData(myArray);
}
}
};
myRequest.open('GET', 'http://example.com/scripts/data.php', true);
myRequest.send();
function parseData(arr) {
console.log(arr);
}
AJAX Basic Example 2
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function(){
if (myRequest.readyState === XMLHttpRequest.DONE) {
if (myRequest.status === 200)
var myArray = JSON.parse(myRequest.responseText);
parseData(myArray);
}
}
};
myRequest.open('GET', 'http://example.com/scripts/data.php', true);
myRequest.send();
function parseData(arr) {
console.log(arr);
}
AJAX Basic Example 3
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function(){
if (myRequest.readyState === 4 && myRequest.status === 200) {
var myArray = JSON.parse(myRequest.responseText);
parseData(myArray);
}
};
myRequest.open('GET', 'http://example.com/scripts/data.php', true);
myRequest.send();
function parseData(arr) {
console.log(arr);
}
AJAX Events and Monitoring
The XMLHttpRequest object allows us to listen for events that occur when the request is being
processed, including progress, errors, and more.
Must add before calling open()
Doesn’t work on file:// protocol
Events:
progress
load
error
abort
loadend – happens at the end of all three (load, error, abort) events. Can not tell which event
happened though. Useful for things that need to happen no matter which event happens.
An event object is the parameter of the event handler function
See section on monitoring progress
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
AJAX Example using event for load
var myRequest = new XMLHttpRequest();
myRequest.addEventListener(‘load’, parseData);
myRequest.open('GET', 'http://example.com/scripts/data.php', true);
myRequest.send();
function parseData(evt) {
console.log(evt);
var myArray = JSON.parse(evt.target.responseText);
// code to process the array and modify the DOM
}
Fetch API
Fetch API is a promise based api for doing AJAX requests.
No support in IE but other modern browsers do support
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
https://developers.google.com/web/updates/2015/03/introduction-to-fetch
fetch('http://example.com/scripts/data.php')
.then(function(response) {
return response.json();
})
.then(function(myJson){
console.log(JSON.stringify(myJson));
});
AJAX Libraries
There is Ajax support built-in to most JavaScript libraries including
jQuery
jQuery ajax support is based on $.ajax(); function
See jQuery docs for API reference
http://api.jquery.com/
Using libraries can simplify your use of Ajax
New native Fetch API is a more modern way to do ajax
Popular AJAX library is Axios
Promise based HTTP client for the browser and node.js
https://www.npmjs.com/package/axios
POST
Send data to a server typically with a POST request
Datatype of the Body of the request is indicated by the Content-Type header
HTML Forms typically submit using a POST request
When sending by form the form tags enctype attribute will determine the content type
application/x-www-form-urlencoded
Keys and values have an = between them
Key-value pairs are separated with an &
Non-alpha characters are percent encoded so not usable for binary data
multipart/form-data
Each value is sent as a block of data in the body with a delimiter between them
Use when binary data needs to be sent
text/plain
If using AJAX to send a request the body can be of any data type you want
application/json is one example for JSON data
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
POST with XMLHttpRequest
You can use the XMLHttpRequest object’s setRequestHeader() method to
set headers on the request.
This is how you would set the Content-Type header to let the server know
what the data type of the request body is.
The XMLHttpRequest object’s send() method can take one parameter.
That parameter is the body of the request
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
POST with Fetch
Fetch defaults to a GET request so to send a POST request you need to use
the optional init parameter to the fetch() method.
The options object is the second parameter to the fetch() method and it is
an object
In that object you can set the body, headers, and request method,
among other things
Headers are set by creating a new Headers object and appending
headers to it before setting it to the headers key in the options object.
The body key can be a list of data types but is typically a string of JSON or
form-urlencoded data
https://developer.mozilla.org/en-US/docs/Web/API/fetch
Global Variables and Namespace
Problem
Variable names need to be unique
All variables by default are placed in the global ”window”
namespace when defined normally with the var keyword unless
defined inside a function. This is Functional Scope. It changes some
with ES6+ let and const and there is Block Scope for those.
Variables defined inside a function are scoped or name spaced to
that function.
If we mix our code with others code, we may overlap variable
names
We want to define our own namespace
We have a few ways we can do that.
Immediately-invoked Function
Expressions (IIFE)
Sometimes called a self executing protecting function
Idea is we wrap our code in an anonymous function that is
immediately executed.
All variables and functions will be locally scoped to that function.
Takes advantage of JavaScript closures
(function(){
//anything in here has its own special namespace
//functions and variables are not available to the outside
})();
The Big Plain Map/Object Literal
Create a global variable and store an object in it
Add all your variables and functions as properties on that object
Useful for quick solution but doesn’t have private variables or any
methods
var myNamespace = {};
myNamespace.aFunction = function(){
};
myNamespace.aVariable = 7;
Exporting a Map to the global
Namespace
(function(){
var myNamespace = {};
//Private variables
var name = “brian”;
//Public members/variables
myNamespace.myName = “brian”;
//Public Method
myNamespace.myFunction = function(){ alert(this.myName)};
window.myNamespace = myNamespace;
})();
Exporting a Map to the global
Namespace with possible
namespace in window already
(function(ns){
//Private variables
var name = “brian”;
//Public members/variables
ns.myName = “brian”;
//Public Method
ns.myFunction = function(){ alert(this.myName)};
window.myNamespace = ns;
})(window.myNamespace || {});
Wrapping with an event function
Another option would be using a window event handler function
listening for an event like DOMContentLoaded to act as your
namespace protector.
Since the event handler is a function, it has function scope and
keeps the variables and functions local to that function.
API, AJAX Demo
We are going to do a short demo application which basically replicates the
breed list functionality on the Dog API site
https://dog.ceo/dog-api/
Open API that returns images of various dog breeds
HTML5 Video & Audio
Built in support for playing audio and video in the browser without plugins like flash or
silverlight
Uses the <video> or <audio> tag for basic support.
Traditionally format/codec support was mixed between browser manufacturers, and
we needed to supply different formats
As of 2016 h.264 mp4 and mp3 is supported in most browsers
In Oct 2013 Cisco announced they would make a h.264 module available to all
You can provide fallback content inside the tag if the browser doesn’t support it
There are attributes for controls, autoplay, loop, preload. See element docs
https://developer.mozilla.org/en-
US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video
https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats
Use examples with VSCode
HTML5 Video & Audio
The <source> tag can be nested inside the <video> or <audio> tag to supply multiple
formats
<video src="http://v2v.cc/~j/theora_testsuite/320x240.ogg" controls>
<p>Your browser does not support the <code>video</code> element.</p>
</video>
<video controls>
<source src="SampleVideo.ogv" type="video/ogv">
<source src="SampleVideo.mp4" type="video/mp4">
<p>Your browser does not support the <code>video</code> element.</p>
</video>
The <video> and <audio> elements have methods attached for controlling playback
https://developer.mozilla.org/en-
US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content
Geolocation
The geolocation API allows the user to provide their location to web applications if they
so desire. For privacy reasons, the user is asked for permission to report location
information.
The API is published through the navigator.geolocation object
getCurrentPosition() method is used to query the browser for a location object
Takes a callback function that runs when the browser responds with a location and also
takes an optional second callback function to run if there is an error
watchPosition() method can be used to continually update the position
navigator.geolocation.getCurrentPosition(function(position) {
do_something(position.coords.latitude, position.coords.longitude);
});
https://developer.mozilla.org/en-
US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API
DEMO using VSCODE
Web Workers
Web Workers provide a simple way for web applications to run scripts in
background threads. Basically, adds a multithreading model to JavaScript
The worker threads do not block or interfere with the user interface or main
thread
The main script and worker scripts post messages to each other and can pass
standard JavaScript data between each other.
This is done with the postMessage() method and the onmessage event
https://github.com/michaeltreat/Web-Worker-Demo
https://developer.mozilla.org/en-
US/docs/Web/API/Web_Workers_API/Using_web_workers
http://www.html5rocks.com/en/tutorials/workers/basics/
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API
https://en.wikipedia.org/wiki/Web_worker
Websockets
The WebSocket Protocol is an independent TCP-based protocol.
WebSocket is designed to be implemented in web browsers and web servers,
but it can be used by any client or server application.
WebSocket is a protocol providing full-duplex communication channels over a
single TCP connection.
Often used for real time data communications from browser to servers.
https://en.wikipedia.org/wiki/WebSocket
https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API
https://html.spec.whatwg.org/multipage/comms.html#network
https://developer.mozilla.org/en-
US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
https://javascript.info/websocket
https://medium.com/@cn007b/super-simple-php-websocket-example-
ea2cd5893575
Reminders
Lab 3 Due, Sunday October 29
Quiz covers Week 8 and ½ of Week 9 lecture. Only variables, audio
and video from Week 9. Due: Thursday, October 26
Lab 4 will come soon
Midterm grades were submitted on October 20 by midnight.
Final exam will be posted on Sunday, December 3 and due by
Thursday, December 7 by midnight. (Final Exam week Dec. 4-9th)
Very similar to the midterm except it will cover all class material and
assignments. No project. 60-75 questions.
Examples of Storage APIs
Short Google video
http://www.html5rocks.com/en/features/storage
Storage API example
https://www.w3schools.com/JS/tryit.asp?filename=tryjs_api_storage_example
Web Storage
https://html.spec.whatwg.org/multipage/webstorage.html
Storage additional items. Get an item that does not exist in the storage
Indexed Database
https://www.w3.org/TR/IndexedDB/
Web SQL Database – This has been deprecated and will no longer be developed or supported in the
future.
https://www.w3.org/TR/webdatabase/
File Access
https://www.w3.org/TR/FileAPI/
https://developer.mozilla.org/en-US/docs/Web/API/File
https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications
Web Storage
Simple and fairly widely supported way to store data in the client
browser.
Simple string only Key/Value storage – IMPORTANT if you want to store a
JavaScript object you must use JSON.stringify() and JSON.parse().
Different than cookies as this is a JavaScript API
There two areas you can store data in
localStorage – persistant storage after browser is closed
sessionStorage – only stores for current browser session
Data is saved per origin and there is a data limit
Firefox is around 10MB
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API
https://developer.mozilla.org/en-
US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
Web Storage
The storage object is exposed on the window object
window.localStorage or just localStorage
You can access key/value pairs in multiple ways
localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting', '#a4509b');
localStorage.getItem('colorSetting’);
localStorage.removeItem('colorSetting’);
There is also a storage event that fires that you can listen for and
react to
Indexed DB
IndexedDB is a low-level API for client-side storage of significant
amounts of structured data, including files/blobs, which also enables
high performance searches of this data using indexes.
Transactional based database system, non-sql based, JavaScript-based
object-oriented database.
Store and retrieve objects based on a key.
Asynchronous API that uses a lot of function callbacks
Storage limits do exist but much larger than Web Storage and differ by
browser
https://developer.mozilla.org/en-
US/docs/Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_crite
ria
https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
Indexed DB
The basic pattern that Indexed DB encourages is the following:
Open a database.
Create an object store in the database.
Start a transaction and make a request to do some database operation, like
adding or retrieving data.
Wait for the operation to complete by listening to the right kind of
DOM event.
Do something with the results (which can be found on the request object).
https://developer.mozilla.org/en-
US/docs/Web/API/IndexedDB_API/Using_IndexedDB
http://code.tutsplus.com/tutorials/working-with-indexeddb--net-
34673
File Access
Allows you to interact with local files using the File API
Can access the file attributes and its data in JavaScript using the
FileReader interface.
Does not allow you to access files on the user's computer without
the user providing them to you with an input of type=file or using the
drag and drop api.
https://web.dev/read-files/
https://developer.mozilla.org/en-US/docs/Web/API/File
We used this link below earlier:
https://developer.mozilla.org/en-
US/docs/Web/API/File/Using_files_from_web_applications
Canvas 2D, Web GL 3D
The HTML Canvas API gives the developer a way to draw graphics
using JavaScript inside an HTML <canvas> element
The Canvas API is primarily a 2D graphics API
Useful for animations, games, data visualization, video and photo
processing, and more
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API
The WebGL API is used to draw 2D and 3D graphics using hardware-
acceleration but still uses the HTML <canvas> element
API is similar to OpenGL ES 2.0
https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API
Go down the page until you see EXAMPLES
We will probably do another lecture on Canvas
Intersection Observer
Provides an API to watch for changes where observed elements intersect
with an ancestor element and it does it asynchronously to not slow down
the UI.
Typically, the ancestor element is the viewport.
Gives a standardized solution instead of old unreliable and slow solutions to
determine this intersection information.
Lazy load images as they are scrolled into the viewport
Create infinite scrolling sites where more content loads automatically as you
scroll
Determine to only run tasks or things like animations if something is in view
Intersection Observer (extra notes)
Popular use
Reporting of visibility of advertisements in order to calculate ad revenues.
Basic set up example:
let options = { root: document.querySelector("#scrollArea"), rootMargin: "0px", threshold: 1.0, };
let observer = new IntersectionObserver(callback, options);
A threshold of 1.0 means that when 100% of the target is visible within the element
specified by the root option, the callback is invoked.
All areas considered by the Intersection Observer API are rectangles; elements which are
irregularly shaped are considered as occupying the smallest rectangle which encloses all
of the element's parts.
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
Canvas 2D, Web GL 3D
The HTML Canvas API gives the developer a way to draw graphics
using JavaScript inside an HTML <canvas> element
The Canvas API is primarily a 2D graphics API
Useful for animations, games, data visualization, video and photo
processing, and more
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API
The WebGL API is used to draw 2D and 3D graphics using hardware-
acceleration but still uses the HTML <canvas> element
API is similar to OpenGL ES 2.0
https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API
Go down the page until you see EXAMPLES
We will probably do another lecture on Canvas
Canvas 2D, Web GL 3D
These are all APIs used for drawing on a <canvas> element on the page using
JavaScript
Canvas is a raster-based where the canvas objects are drawn in immediate mode.
Once the item is drawn to the canvas it is forgotten. If you are doing animation, you
redraw the entire scene each frame. You can not modify something once it has been
drawn to the canvas.
This is different than Scalable Vector Graphics (svg) which is vector-based and the
shapes are remembered as objects in the DOM and then rendered to a bitmap on
the screen when the HTML renders. If a svg object attribute is changed then the
browser can automatically re-render.
https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg
There are many libraries for canvas that add scene-graph capabilities to the canvas
element.
Very low level api. Much easier to use a library, especially for hit detection.
Animation
Animation can be canvas, web gl, or just dom
manipulation
Animation requires rendering a scene with changes at a
frame rate
Old way is with setInterval() – new way is with
requestAnimationFrame()
https://css-tricks.com/using-requestanimationframe/
Canvas Basics
Tag is canvas.
Should set width and height in html but you can also change it with css.
Need an id to select it.
Fall back content can be provided inside the canvas tag.
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations
<canvas id="stockGraph" width="150" height="150”>
current stock price: $3.15 +0.15
</canvas>
<canvas id="clock" width="150" height="150">
<img src="images/clock.png" width="150" height="150" alt=""/>
</canvas>
Rendering Context
You need to get the rendering context to run the drawing commands on
You can test for canvas support by seeing if the getContext function exists
let canvas = document.getElementById('tutorial');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
// drawing code here
} else {
// canvas-unsupported code here
}
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
The Grid
The canvas is our coordinate space.
The top left is (0, 0) and it is as wide and tall as the canvas element
Normally one grid unit corresponds to one pixel
Grid units can be fractional
Be careful drawing lines that do not align with the
grid lines. They can not cleanly convert to pixels.
Styles and colors
In general these properties use css syntax
Two basic ones
fillStyle = color Sets the style used when filling shapes.
strokeStyle = color Sets the style for shapes' outlines.
// these all set the fillStyle to 'orange’, ctx is the 2d context
ctx.fillStyle = "orange";
ctx.fillStyle = "#FFA500";
ctx.fillStyle = "rgb(255,165,0)";
ctx.fillStyle = "rgba(255,165,0,1)";
Other properties described here.
https://developer.mozilla.org/en-
US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors
Rectangles
Canvas only has one primitive shape, the rectangle
These are functions on the context
fillRect(x, y, width, height) Draws a filled rectangle.
strokeRect(x, y, width, height) Draws a rectangular outline.
clearRect(x, y, width, height) Clears the specified rectangular area,
making it fully transparent.
Vcode demo 1 and 2
1, 2
Paths
The only other primitive is paths
1. Create the path
2. Use drawing commands to draw into the path
3. Close the path
4. Fill or stroke to render the path
Reminders
Attendance is 15% of your grade and is being taken each week
for in person students.
Quiz Week 9 lecture. Due: Thursday, November 2
Lab 4 will come soon
Final exam will be posted on Sunday, December 3 and due by
Thursday, December 7 by midnight. (Final Exam week Dec. 4-9th)
Very similar to the midterm except it will cover all class material
and assignments. No project. 60-75 questions.
Quick Review #1
What will the following code draw?
ctx.beginPath();
ctx.fillStyle = 'rgb(0,255,0)';
ctx.rect(45,45,100,100);
ctx.stroke();
A.Blue rectangle
B.Green rectangle
C.Red rectangle
D.Green square
E.None of the above
Quick Review #2
What will the following code draw?
ctx.beginPath();
ctx.fillStyle = 'rgb(255,0,0)';
ctx.rect(90,90,100,120);
ctx.fill();
A.Blue rectangle
B.Green rectangle
C.Red rectangle
D.Red square
E.None of the above
Paths
1. beginPath() Creates a new path. Once created, future drawing
commands are directed into the path and used to build the path up.
2. Path methods Methods to set different paths for objects.
3. closePath() Closes the path so that future drawing commands are once
again directed to the context.
4. stroke() Draws the shape by stroking its outline.
fill() Draws a solid shape by filling the path's content area.
Vcode Demo 3
Path Methods
Move the pen without drawing
moveTo(x, y)
Drawing straight lines
lineTo(x, y)
Draw arcs or circles (measured clockwise from the positive x axis and expressed in radians)
Convert to degrees with this formula: (Math.PI/180)*degrees
arc(x, y, radius, startAngle, endAngle, anticlockwise)
arcTo(x1, y1, x2, y2, radius)
Bezier and quadratic curves
quadraticCurveTo(cp1x, cp1y, x, y)
Change values to create an image for point and area calculations. Click on link to play in real time.
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
Rectangles added to the current path vs rectangle primitive
rect(x, y, width, height)
Vcode Demo 4,5 (3 versions), 6
View code. Guess what it will look like before running it
3,4,5,6
Path 2d
The path 2d object allows you to cache or record drawing commands.
All path methods like moveTo, rect, arc or quadraticCurveTo, etc., which we
got to know above, are available on Path2D objects.
Path2D() The Path2D() constructor returns a newly instantiated Path2D object,
optionally with another path as an argument (creates a copy), or optionally
with a string consisting of SVG path data.
new Path2D(); // empty path object
new Path2D(path); // copy from another Path2D object
new Path2D(d); // path from SVG path data
Can also take in svg data
7
Drawing Text
Two methods for drawing text
fillText(text, x, y [, maxWidth]) Fills a given text at the given (x,y) position.
Optionally with a maximum width to draw.
strokeText(text, x, y [, maxWidth]) Strokes a given text at the given (x,y)
position. Optionally with a maximum width to draw.
measureText() Returns a TextMetrics object containing the width, in pixels,
that the specified text will be when drawn in the current text style.
Text properties here
https://developer.mozilla.org/en-
US/docs/Web/API/Canvas_API/Tutorial/Drawing_text
Vcode Demo 8
8
Images
Importing images into a canvas is basically a two-step process:
Get a reference to an HTMLImageElement object or to another canvas
element as a source. It is also possible to use images by providing a URL.
Draw the image on the canvas using the drawImage() function.
Be careful to wait until the image is loaded before using. Helpful to use the
images onload attribute to trigger a callback function
drawImage function has a few different signatures
https://developer.mozilla.org/en-
US/docs/Web/API/Canvas_API/Tutorial/Using_images
Vcode Demo 9
9
Transform
To do transforms you must transform the context or grid and then draw into it. When
you are done you need to undo that transform.
The save and restore function are helpful there and can also be used to save other
context states like colors.
save() Saves the entire state of the canvas.
restore() Restores the most recently saved canvas state.
We will look at the transforms here
https://developer.mozilla.org/en-
US/docs/Web/API/Canvas_API/Tutorial/Transformations
Vcode Demo 10
10
Basic Animation
1. Clear the canvas
2. Save the canvas state
3. Draw the animated shapes
4. Restore the state
You also need a way to trigger your draw frame function on an interval
setInterval(function, delay) Starts repeatedly executing the function specified
by function every delay milliseconds.
setTimeout(function, delay) Executes the function specified by function in
delay milliseconds.
requestAnimationFrame(callback) Tells the browser that you wish to perform an
animation and requests that the browser call a specified function to update an
animation before the next repaint.
https://developer.mozilla.org/en-
US/docs/Web/API/Canvas_API/Tutorial/Basic_animations
Vcode Demo 11 11
Canvas Libraries
There are canvas libraries that make this easier
EaselJS is one that turns the canvas into a retained mode drawing
context
http://www.createjs.com/easeljs
http://code.tutsplus.com/tutorials/using-createjs-easeljs--net-34840
WebGL
WebGL is a JavaScript API that allows 2d and 3d rendering using an
API very close to OpenGL ES 2.0 and usually uses hardware
rendering in compatible browsers.
Difficult to work with if you are not familiar with OpenGL
https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API
There are libraries that make it easier but still much more complex
than canvas 2d
ThreeJS is one of the most popular
http://threejs.org/
Reminders
Attendance is 15% of your grade and is being taken each week
for in person students.
Quiz Week 10 lecture. Due: Thursday, November 9
Lab 4 will come soon
Final exam will be posted on Sunday, December 3 and due by
Thursday, December 7 by midnight. (Final Exam week Dec. 4-9th)
Very similar to the midterm except it will cover all class material
and assignments. No project. 60-75 questions.
Location
The Location object/interface represents the URL of the Window or
Document object
It provides properties and methods to access and change the
individual parts of a URL in the browser's location bar
location.href is a string version of the entire url and if replaced
with a new value, the browser will navigate to the new location
https://developer.mozilla.org/en-US/docs/Web/API/Location
History API
The History API provides JS access to the session history in the browser
It is exposed by the window.history object
Provides methods and properties to allow you to navigate through the user’s history
and make changes to the user’s history
Move back and forward with the back() and forward() methods
Go to a specific location with the go() method
The pushState() and replaceState() methods can be used to add or modify a
history state
READING MATERIAL
https://developer.mozilla.org/en-US/docs/Web/API/History_API
https://developer.mozilla.org/en-
US/docs/Web/API/History_API/Working_with_the_History_API
Date Object
JavaScript Date object is the representation of one moment in time and is
stored in a platform-independent format
It contains a Number which is the milliseconds since January 1, 1970, UTC
Provides numerous methods to access the individual date components in
local time or UTC time
See VsCode dateObject demo
READING MATERIAL only no working demo
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Date
Math Object
The Math object is a built-in object that provides many
mathematical functions and constants
It does not have a constructor. All properties and methods are
called on the object not an instance of the object (static).
Works with Number types but not BigInt types
Some methods to take note of are floor(), ceil(), random()
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Math
Math Object
Here, the side of the given equilateral
triangle is 6 cm.
a = 6 cm
h = (√3/2)a = (√3/2) × (6) = 3√3 cm
Using trigonometric functions
Tan(60) = h/3
H = 3*tan(60)
Calculate using VSCode and math
objects. Go to VSCode Math Demo
Image Object
The Image object is used to create a new instance of the
HTMLImageElement
Equivalent to using document.createElement(‘img’)
As soon as the src attribute is set the image will begin to download
and you can listen for an onload event to do something
We saw an example of using the Image object in the canvas
examples
https://developer.mozilla.org/en-
US/docs/Web/API/HTMLImageElement/Image
Array Object
Array is an object in JavaScript, not a primitive
Allow for a collection of objects/values to be stored in a single variable and in a
set order
Resizable and can contain mixed data types
Must be accessed using the non-negative integer indexes and the array is zero-
indexed
Length property will return the number of items in the array
Built-in array copy operations make shallow copies
Created with the Array() constructor or just []
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array
Use VSCode to demonstrate. Go to Array Demo.
Array Object
Provides many methods and properties to work with arrays
Useful static methods include from(), isArray(), of()
Can use the at() method to get an item at a given index (pos or neg)
forEach() method will run a given function for each item in the array
Multiple methods for searching through arrays
push() and pop() to add an element to the end or remove and return
the last element
splice() for adding or removing elements from the array at given
positions, works on existing array, vs slice()
Quick Quiz
1. MATH.SQRT(-0) = -0
A. True
B. False
2. MATH.SQRT(-25) = -5
A. True
B. False
Helpful Array Methods
Here are a few array methods you should know. The important part
here is they work in a functional way. They do not modify the input but
instead return a new array.
map()
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
filter()
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
reduce()
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
concat()
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
Bind, Call, Apply
All methods implemented on the global Object and used with
functions
bind() – creates and returns a new function with the value of this set
to the argument
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
call() – way to call a function with a value of this given as an
argument. Also takes additional arguments individually.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
apply() – way to call a function with a value of this given as an
argument. Also takes additional arguments as a single array.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
Node JS
Open-source JavaScript runtime environment built for back-end use
instead of in-browser use.
Built on the V8 JavaScript Engine from Chrome
Can be used for CLI applications or server-side scripting and applications
Event-driven asynchronous architecture
Optimizes throughput and scalability
Initially written by Ryan Dahl in 2009
Governed by the OpenJS Foundataion after it was created by the
merger of the Node.js Foundation and the JS Foundation
https://en.wikipedia.org/wiki/Node.js
https://nodejs.org/
Node Project Setup
NPM – or "Node Package Manager" – is the default package manager for JavaScript's
runtime Node.js.
Go over basics of creating node-based projects
npm init to initialize projects
npm install or npm i to install local node modules to your project
--save to save dependency to package.json - defaults to this without flag now in
current versions
--save-dev to save dependency as a development dependency
npx will run local project binaries found in the node_modules folder
There is an alternative package manager called yarn that many people use instead
of npm. It was created by Facebook to enhance npm. Npm has now adopted
many of the thing's yarn introduced. Fully compatible with npm.
Has an example:
https://www.w3schools.com/nodejs/nodejs_npm.asp
ES6 Modules
ES6 Modules provide a way to split up your JavaScript code into separate
modules and only import what is needed when you need it.
NodeJS has a module system implemented with CommonJS.
There have been other libraries and frameworks (CommonJS, AMD, UMD)
that have enabled modules in JS but ES6 Modules is a native
implementation.
Most modern browsers support the ES6 syntax directly.
ES6 modules are used heavily with frameworks like React and tools like
webpack
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
ES6 Modules
What do we get?
Modules can be more easily reusable. Code can be put in smaller
files that encapsulate functionality and can be shared between
different applications.
All the code in a ES6 module is private by default and executes in
strict mode. You must explicitly export what you want to use outside
the module.
Helps solve issues with namespace and naming conflicts.
ES6 Modules
Creating Modules
ES6 modules are stored in JS files. There is exactly one module per file and one
file per module.
You can have named exports and/or a single default export
You can export things like variables, objects, classes, functions.
Use the export keyword
Named exports
export function add(){}
export const PI = 3.1415;
Default exports – use export default, can be anonymous, only one per module
export default function(){}
export multiple named exports also as default
export default {add, Car, PI};
ES6 Modules
Importing Modules
Import statement used to access what export has made available in a module
Imports must be in the top level of a module (first lines in file or script tag)
Import and export can only be used in script tags that add the type=“module”
attribute. This goes for both external and embedded.
ES Modules do not work with file:// protocol
Automatically runs in strict mode
Adding module code to an HTML page
<script type=“module” src=”./module.js”></script>
<script type=“module”>
import statements
Embedded JS Code
</script>
ES6 Modules
Import Statements
Default import:
import localName from 'src/my_lib’;
Namespace import: imports the module as an object (with one property per named export).
import * as localName from 'src/my_lib’;
Named imports:
import { name1, name2 } from 'src/my_lib’;
Renamed imports
import { name1 as localName1, name2 } from 'src/my_lib’;
import { default as localName } from ‘src/my_lib’;
Combining imports (default must come first):
import theDefault, * as localName from 'src/my_lib’;
import theDefault, { name1, name2 } from 'src/my_lib’;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
https://exploringjs.com/es6/ch_modules.html#sec_importing-exporting-details
ES6 Modules Examples
Examples
The "modules" directory contains a series of examples that explain how JavaScript
modules are used. The subdirectories are as follows:
•basic-modules: Simple example that demonstrates module basics, including default exports
(run the example live).
•renaming: Shows how exports can be renamed to avoid conflicts, using x as y syntax (run
the example live).
•module-objects): Shows how to import an entire module as an object using import * as x
from 'y.js' syntax (run the example live).
•classes: Provides an example of importing a class from a module (run the example live).
•module-aggregation: Shows how sub module features can be aggregated into a parent
module using export { x } from 'y.js' syntax (run the example live).
•dynamic-module-imports: Demonstrates dynamic module loading using import().then() (run
the example live).
•top-level-await: An example of using the await keyword within a module (run the example
live).
ES6 Module Resources
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Guide/Modules
https://exploringjs.com/es6/ch_modules.html#sec_modules-in-
browsers
Important information to read. Read over the 3 Scenarios.
https://www.freecodecamp.org/news/how-to-use-es6-modules-
and-why-theyre-important-a9b20b480773/
https://www.sitepoint.com/understanding-es6-modules/
https://www.bignerdranch.com/blog/default-exports-or-named-
exports-why-not-both/
Babel
Babel is used to convert JSX to plain JavaScript React calls.
Babel can also compile our ES6+ to ES5
Babel can be directly used in the browser for development purposes
<script src="https://unpkg.com/babel-
standalone@6/babel.min.js"></script>
<!-- Your custom script here -->
<script type="text/babel">
const getMessage = () => "Hello World";
document.getElementById('output').innerHTML = getMessage();
</script>
Need to configure the babel presets or it won’t do anything. Typically, in a
.babelrc or babel.config.json file. Need to load modules for the presets you want
to use and then add them to the config.
https://babeljs.io/setup#installation
ReactJS
JAVASCRIPT LIBRARY FOR BUILDING
USER INTERFACES
React JS
Watch 100 second video first
Created at Facebook by software engineer Jordan Walke
An early prototype in 2011 (FaxJS) shipped as a search element on Facebook. Jordan then
worked on a prototype for the hard to manage Facebook Ads which became react.
Deployed in newsfeed in 2011 and instagram.com in 2012 after Facebook acquired them.
Open sourced at JSConf US May 2013
Used to build interactive user interfaces for applications that have frequent data changes.
When the components internal data changes it automatically updates the markup.
Can be used to build UI components, single page applications (SPA), and iOS, Android or
UWP when using React Native.
https://en.wikipedia.org/wiki/React_(JavaScript_library)
https://reactjs.org/
React JS
What is React? A library for building user interfaces.
Composition, Unidirectional Dataflow, Explicit Mutations, Just JavaScript
You compose a user interface with components
Component Based - Components are encapsulated chunks and manage
their own state and can be nested inside each other
Component logic is all in JavaScript and there are no HTML templates used
Data is passed to the component through properties or props with a one-way
data flow
Properties or props are a set of immutable values that gets passed to the
components render function
Components should not directly modify the values in props. Instead pass
callback functions from the parents via props.
React JS
Uses a “Virtual DOM” in the background and only updates the visible
DOM when needed, including only updating the parts that need to.
Can be used to build single page application or just components on
an existing website or web application
It can be directly used in the browser in a script tag or with a bundler
to package all the JS files in one big file.
Works well as a node js project. All modules used are typically node
modules.
There is a Create React App node package that will produce a
skeleton app as a starting point with a preconfigured build pipeline.
https://reactjs.org/docs/getting-started.html
https://reactjs.org/docs/react-api.html
Stopped here on 11/14/2023
React JS - Composition
You compose the UI out of multiple components. It looks like HTML but it is how
something might be built out of react components.
<Container>
<NavBar />
<Header />
<DatePicker>
<Calendar />
</DatePicker>
<Footer />
</Container>
React JS – Unidirectional Dataflow
In a React app data flows from parent component to child component
Data is passed as props to the component and the props are
immutable
If a component needs to save data/state it needs to do that in itself or
get that data as props from a parent
Props are added to a component as attributes of the component (in
JSX) or as the second argument to a createElement() function call
Different than a normal JS/Jquery app that is all event driven and just
listening for events and modifying the DOM directly
Remember Data flows down to the component and is immutable
<HeaderComponent name=“brian” />. This is considered a prop. A
prop looks like an attribute on an HTML.
If you need to pass data back up the chain, you need to pass down a
function to run and call that function within the component
React JS – Explicit mutations
You will explicitly change or mutate the components state to update the
component. If data needs to change in the app you have to explicitly tell it
that the data is changing.
This makes mutations explicit
You use the setState() function to trigger this state mutation and pass it the
updated state items
this.setState({
name: ‘brian’,
class: ‘itmd4565’
})
Can also pass setState() a function that looks at the known good previous
state
this.setState(prevState => ({
seconds: prevState.seconds + 1
}))
React JS - JSX
Can use an optional JSX syntax in your JavaScript code although
typically JSX is used
JSX is a JavaScript syntax extension
This allows us to use what looks like HTML tag syntax to render our
components.
If we don’t use JSX we need use the React.createElement() function
in its place
JSX allows you to evaluate JavaScript expressions in your JSX with curly
brackets { }
Custom HTML attributes are passed in but need to start with data-
Since JSX is not supported by browsers or runtimes you need to convert
it to plain JS with a tool like babel.
https://reactjs.org/docs/introducing-jsx.html
React JS – React Elements
Fundamental object and concept in React apps
A React element is a JavaScript object representation that describes how you would
like it to appear on the screen. This is a JavaScript representation of a DOM Node.
Use React.createElement() to create an element. Most fundamental piece.
All JSX will be converted to React Elements by babel
React.createElement( type, [props], [...children] )
const element = React.createElement(
‘div’,
{id: ‘button’},
‘Login Now’
)
If you are not passing props use null, props should be an object
React JS – ReactDOM
React does not provide a way to use elements in a web page by itself
react-dom provides the DOM-specific methods that you can use to interact
with the DOM in a web page
We use the ReactDOM.createRoot().render() method to render a React
element into the web DOM
const container = document.getElementById('root');
ReactDOM.createRoot(container).render(<App />);
https://reactjs.org/docs/react-dom.html
Click on createRoot. Example near the bottom
https://reactjs.org/docs/react-dom-client.html
React JS - Components
A component is a function or a Class which optionally
accepts input and returns a React element.
React components can be function based or class based
React component names should start with a capital letter
Optionally input via props are passed into the function or class
A component always returns a React element
If your component needs to save any data or state within the
component, you need to use a class and save the data in the
components state.
No DEMOS. Great reading material especially for render()
https://reactjs.org/docs/react-component.html
React JS – Functional Components
Stateless functional components can be written as a simple function
function HelloHeader(props){
return (
<h1>Hello World!</h1>
);
}
Or
const HelloHeader = (props) => {
return (
<h1>Hello World!</h1>
);
}
ReactDOM.createRoot(container).render(<HelloHeader />);
React JS - Components
Components should be designed as small possibility reusable
elements that are added to a react app.
The only required method in the component class is the render()
function
A basic example is below
Class HelloHeader extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}
React JS - Components
The same basic component is below without JSX
Class HelloHeader extends React.Component {
render() {
return React.createElement(‘h1’, null, ‘Hello World!’);
}
}
https://reactjs.org/docs/react-without-jsx.html
React JS - Components
Components can use other components.
Class HelloHeader extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}
Class Page extends React.Component {
render(){
return(
<div>
<HelloHeader />
</div>
);
}
}
React JS – Data Flow
Data flows from parent to child via properties and are available in the child
with this.props. And properties are immutable.
Class HelloHeader extends React.Component {
render() {
return <h1>Hello {this.props.name}</h1>;
}
}
Class Page extends React.Component {
render(){
return(
<div>
<HelloHeader name=’Brian’ />
</div>
);
}
}
React JS – Data Flow
Inverse Data Flow – Child to Parent
Pass a parent's event handler as a property on the child then in the child call that
handler to pass data back to the parent for setting state or something else.
Class Page extends React.Component {
render(){
return (
<MainHeader />
<Greeting searchFunction={this.searchHandler}>Hello
World!</Greeting>
<MainFooter />
);
}
searchHandler(e){
console.log(e);
}
}
React JS – State
State is place we can store data in a component and change the data to see a
reflection in the UI.
It is available in the this.state object in class components
Must add a constructor to your class and initialize the state there.
class App extends React.Component {
constructor(props) {
super(props);
this.state = { header: "Header from state...", content: "Content
from state..." }
}
render() {
return (
<div><h1>{this.state.header}</h1><h2>{this.state.content}</h2></div> );
}
}
Try to make the state as simple as possible and keep as many components stateless as
possible. If you have many components that need state, you should make a parent
component that has the state in it and pass it down through props.
React JS – State
Do not try to modify the state object directly
// Wrong
this.state.comment = ‘Hello’;
// Correct
this.setState( { comment: ‘Hello’ } );
Or this.setState((currentState) => { return new state});
If you need to set state in one component from another you need to pass
handlers down to the child component that then calls setState() in the parent
that has the state object.
The React library watches this state and when it detects changes it compares
it to the browser DOM and updates only what is necessary
Great Demo in CodePen
https://reactjs.org/docs/state-and-lifecycle.html
Controlled Components
In React when a form controls data and value is managed by the
component’s state is is called a controlled component.
This leads to a single source of truth, the value in state. The value in
state is the value you would submit to any server processes.
You use the value in state to populate the controls value attribute and
update the value in state when the user makes a change.
https://reactjs.org/docs/forms.html#controlled-components
DEMOS:
https://www.w3schools.com/react/default.asp
https://www.w3schools.com/react/tryit.asp?filename=tryre
act_getstarted_class
Front-end vs Back-end
Every web application can be broken down into the two part
Front end is what is delivered to the user’s browser for the user to interact with
Back end is what code is running on the server(s) that handles much of the
business logic and responds to requests from and interacts with the front end
Why do we use back-end code?
Security – Some of our code needs to be able to be trusted
Data validation, data security, user/session management, authorization, etc
Performance
More resources for data-intensive computation that can happen closer to the data store
Ability to avoid processing duplicate requests with caching at different layers
Compatibility
We can make a universally compatible API for other front-ends or deliver dynamic content by
rendering the HTML templates on the server before delivering them to the client.
Front-end vs Back-end
There is some considerations for where we put our logic and parts of our
application
The front-end typically has the UI and presentation that the user interacts with
and some logic
The back-end typically handles persistent storage to something like a database
and all the application business logic
The back-end would also provide access to some type of API for the front-end
whether that is a traditional web API or something like a JSON API.
Logic in the front-end can be very responsive for the user but can have
considerations for security, capabilities, performance, and code reuse.
Logic in the back-end is much better handling security, heavy computation,
compatibility, and can easily be used with different clients or front-ends
Back-end Components
Servers / Infrastructure
Databases / Persistent Storage
Languages
Frameworks
Architectures
APIs
Servers / Infrastructure
Traditional basic setup consisting of a server running all the app code,
a database that the server talks to, and the client
This would be considered a simple monolithic design
App Code
Code
www Dependencies
Client Server Database
Servers / Infrastructure
These days most companies rent server capability (VMs) from cloud
providers instead of owning and managing their own hardware
IaaS - Infrastructure as a Service
VMs and other virtualized hardware is used instead of physical hardware
Additional VMs can be launched if capacity is needed vs buy more hardware
PaaS – Platform as a Service
Cloud providers handle all the underlying VMs and all the company needs to
due is upload their backend app code.
Google App Engine, Azure App Service, Amazon Elastic Beanstalk
SaaS – Software as a Service
A company provides the backend and an API others can use
Servers / Infrastructure
If you need to scale due to traffic increases,
you will just add additional servers typically App Code
behind a load balancer
App Code
Code www
Client
App Code
Database
Load
Balancer
Servers/VM
Servers / Infrastructure
What problems does this monolithic design bring?
Each server/vm needs the entire app code base and all
dependencies or modules being used
Updating one part of the application requires us to redeploy the
entire application
What is one part of the application is just needing more resources?
These issues and more have brought about the popularity of
microservices architecture and serverless applications
Microservices
App gets broken up into smaller apps that focus on one particular part of
the application
Each of these smaller apps have their own infrastructure and it can be the
same or different from the others
Each of these services provide an API to allow them each to communicate
with each other
They can be added, upgraded, reused, and developed independently
There are companies out there that provide these small services that you
can plug into your application. For example, there is twilio that runs an
email sending and messaging service.
Serverless
This is a cloud computing model where the app does not run on
dedicated VMs or containers that the customer manages
Does not continuously use resources
Resources are used only during the processing of a request
Typically, code is deployed as a cloud function that runs on certain
requests
The cloud vendor provides the underlying infrastructure and will
scale up as needed.
Persistent Data Storage
Primary Databases
MySQL
PostgreSQL
Oracle
Microsoft SQL
MongoDB
Additional Data Storage Technologies
Caching with redis, memcache, varnish, or others
Cloud Database services
Cloud File BLOB storage
Popular Languages
Early backend web languages like PHP and ASP allowed you to mix code logic in your
HTML files to provide dynamic content which led to what some call spaghetti code
Newer versions of those language and the others tend to have a more structured
approach
Most languages now have package managers that are used to manage dependencies
PHP - Composer
ASP / C# - NuGet
JavaScript (NodeJS) - npm
Python - Pip
Ruby – RubyGems, Bundler
Java / JSP - Maven
Popular Frameworks
Now days most people start with a web framework.
More secure and quicker than writing all the pieces from the ground up
PHP – Laravel, Symfony, CakePHP, CodeIgniter, Zend Framework, and more
ASP / C# - ASP.net and MVC
JavaScript (NodeJS) – Express, NextJS
Python – Django, Flask, web2py, Pylons, Pyramid, and more
Ruby – Ruby on Rails
Java / JSP – Spring, JSF, and more
APIs (start here for day 2)
API – Application Programming Interface
The public interface for interacting with a back-end
The list of all the different types of requests and their endpoints
Requests that are not allowed should respond with an error
Various types of API design that use different methods and URIs
REST representational state transfer – most common, used for exchanging data
and resources
SOAP - simple object access protocol – messaging standard by W3C and uses
XML
RPC – remote procedure call – used to invoke actions or processes and uses
JSON or XML
GraphQL – Uses POST at a single endpoint for all queries
REST
Type of request has special meaning and url path can be the same or
different from other types
APIs that use this naming convention and follow the other aspects of
REST are considered a RESTful API or REST API
Defined by Roy Fielding in his 2000 Ph.D. dissertation
Fielding, Roy Thomas. Architectural Styles and the Design of Network-based
Software Architectures. Doctoral dissertation, University of California, Irvine,
2000.
https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
https://www.ics.uci.edu/~fielding/pubs/dissertation/fielding_dissertation.pdf
Fielding helped design HTTP 1.1 and generalized URLs to URIs using this
research
REST
Six architectural constraints
Uniform interface
A resource in the system should have only one logical URI, and that should provide a way to
fetch related or additional data
Client-server
Client and server applications must be able to developed independently
Stateless
each request contains all information necessary to service request and the response
Cacheable – High performance
Layered system
client cannot determine if it is connected to end server or intermediary along the way
Code on demand (optional)
Most of the time you would send a resource representation using XML or JSON but you can
return executable code
REST CRUD
POST = create something - Create HTTP
Main
POST /contacts Actions methods
GET = get something - Read Create POST
GET /contacts Read GET
Safe method with no side effects only retrieves data Update PUT
DELETE = delete something - Delete Delete DELETE
DELETE /contacts/2
PUT = update/replace something - Update/Replace
PUT /contacts/2
PATCH = update/modify something – Update/Modify
PATCH /contacts/2
REST Example
You work at an ice cream shop and you’re trying to build a web application
to show the flavors of ice cream that are in stock that day and allow the
workers to actually make updates to those flavors
How do you do this?
With a REST API
You have your web app or web page communicate with a cloud-based
server via a REST API
REST API
REST Example
Example of an endpoint
HTTP://icecream.com/api/flavors (note flavors is a resource)
Response
REST API
Request
REST Example
HTTP://icecream.com/api/flavors (note flavors is a resource)
REQUEST RESPONSE
Header
Operation End Point
Parameter/Body
REST Example
HTTP://icecream.com/api/flavors (note flavors is the resource)
Step 1. We want to retrieve the flavors. What does our REST API request look like?
REQUEST RESPONSE
Header [ { “id” : 0,
This might be an API Key or some
authentication data “flavor”: “strawberry”},
Operation End Point { “id” : 1,
GET /api/flavors
Parameter/Body “flavor”: “mint choc”} ]
REST Example
HTTP://icecream.com/API/flavors (note flavors is the resource)
Step 2. What happens when mint chocolate runs out? We want to replace it with chocolate.
REQUEST RESPONSE
Header ID is 1 { “id” : 1,
“flavor”: “chocolate”}
Operation End Point
PUT /api/flavors/1
Parameter/Body
{“flavor”: “chocolate”}
REST Example
HTTP://icecream.com/API/flavors (note flavors is the resource)
Step 3. We just received a new flavor called Lemon Raspberry. We want to load this new
ice cream up into your website. So, we are creating.
REQUEST RESPONSE
Header No ID { “id” : 2,
Operation End Point “flavor”: “Lemon Raspberry”}
POST /api/flavors
Parameter/Body
{“flavor”: “Lemon Raspberry”}