Standard markup language for documents designed to be displayed in a web browser - founded in 1993 by Tim Berners-Lee
In 1993 Mosaic emerged as the first graphical browser, had challengers though in the form of Netscape (1994), Internet Explorer (1995) and others
<!DOCTYPE html>
- informs web browsers which version of HTML is being used and is
placed at the very beginning of the HTML document.
<html>
is “opening tag”, </html>
is “closing tag” - Our entire
web
page
needs to be wrapped in html tags.
<html lang="en">
- Document language. A web page's default language is defined by
the
lang
attribute on the top-level html
element.
<head>
- contains all of its metadata, like the page title, any CSS stylesheets
<meta charset="utf-8">
- Character set. UTF-8 is sort of like a universal alphabet
for
the
Internet, every web page you create should
have this line in its head.
<title>
- one of the most important pieces of metadata, browsers display this in
the
tab
of the page
<body>
- bulk of our HTML markup will live in the body element, which represents
the
visible content of the page.
<!--
HTML comment syntax -->
Best practice for using Meta tags:
Elements are identified by the use of angle brackets <>
,
surrounding the element name (define the structure and content of objects within a page).
The use of angle brackets <>
surrounding an element creates what is known as a
tag (most commonly occur in pairs of opening and closing tags).
Attributes are properties used to provide additional information about an element (always specified in the start tag, come in name/value pairs).
Paragraphs <p>
are represented in visual media as blocks of text
separated from
adjacent blocks by blank lines and/or first-line indentation (should only contain inline elements).
Formatting tags:
<b>bold tag</b>
<i>italic tag</i>
<u>underline tag</u>
<s>strikethrough tag</s>
<ins>inserted tag</ins>
<sup>tag</sup>
<sub>tag</sub>
<small>small tag</small>
<mark>mark tag</mark>
<del>del tag</del>
iframe tag - used to embed another document (google map, youtube)
<iframe>tag</iframe>
<H1>
define the outline of the site, have syntax and semantics<header>
denotes introductory content for a section, article,
or
entire web page (wrap a website's name/logo and main navigation)<nav>
lets you mark up the various navigation sections of
your
website<div>
doesn't alter the semantic structure of a page, for
block-level content<span>
doesn't alter the semantic structure of a page, for
inline
content<article>
used to identify a section of independent, self-contained content
that may be independently distributed or reused
<section>
used to identify a thematic grouping of content<aside>
holds content, such as sidebars, inserts, or brief explanations, that
is tangentially related to the content surrounding it<footer>
basically the same as headers, except they generally
come at end of an article/website (copyright notices, footer navigation, author
bios)<time>
represents either a time of day or a calendar date
(datetime attribute)<address>
defines contact information for the author of the
article or web page in question Article by Someone Skopje, Macedonia
<figure>
represents a self-contained "figure", like a
diagram,
illustration, or even a code snippet<figcaption>
associates a caption with its parent figure
element
<main>
represents the dominant content of the body of a
document
(only once per page)<progress>
displays an indicator showing the completion
progress
of a task, typically displayed as a progress bar <details>
creates a disclosure widget in which information is
visible only when the widget is toggled into an open state <summary>
specifies a summary, caption, or legend for a
details
element's disclosure box<label>
like article or figcaption, but for form labels<input>
creates a text field (variable that gets sent to the backend server)
<select>
represents a control that provides a menu of options<textarea>
represents a multi-line plain-text editing control (sizeable
amount of free-form text)<button>
when activated, performs an action, such as submitting a form or
opening a dialog<cite>
define the title of a work that is included in the document The
Scream E. MunChapter 1893.<mark>
an easy way to achieve a highlighting effect<meter>
allows us to generate a visual image based on provided values
(display a measurement on a known scale)List element is used to create lists of items on a webpage
<ul>
list<li>
element<ol>
list<li>
are the same (can be numerical or
alphabetical)<dl>
list<dt>
instead of <li>
<dd>
for indentationStyling lists
list-style-type
- sets the marker (such as a disc, character, or custom counter
style) of a list item elementlist-style-image: url("image.gif");
- sets an image to be used as the list item
markerlist-style-position
- sets the position of the ::marker relative to a list item
list-style
- allows you to set all the list style properties at onceLinks (inline element) are created with the <a>
element, which stands
for
“anchor”, href
attribute
determines where
the user goes when they click.
<a href="images.html" target="_blank" >images</a>
href: reference to location of new content (where to go on click)
content: the “clickable” part (text or image) >images<
<a href="images.html">images</a>
<a
href="../../images/images.html">images</a>
<a href="/">home page</a>
target attribute has a few pre-defined values that carry special meaning for web browsers, but the most common one is _blank, which specifies a new tab or window.
To create an email link, the href attribute value needs to start with mailto:
followed by the email address to which the email should be sent
<a href="mailto:name@gmail.com">Email</a>
Linking to parts of the same page (first setting an id attribute on the element we
wish to link to) <a href="#top">Back to top</a>
Image content is defined outside of the web page that renders it, included in web
pages
with the
<img>
tag and its src attribute
<img src="images/mochi.jpg" alt="description" title="title"/>
HTML form elements let you collect input from your website's visitors (mailing lists, contact forms, blog post comments). A form must be surrounded by the form element tags (usually is accompanied with method and action attributes).
<form action="processor.php" method="post" class="speaker-form"><form/>
Checkbox input elements are rendered by default as boxes that are checked when activated (allow users to select multiple values and tie them all to one control name). Common way - send the data for checkboxes to the server in an array.
<label class="checkbox-label" for="available"> input id="available" name="available type="checkbox" value="is-available"/>
<span>Example of a checkbox</span></label>
Select (dropdown) element represents a control that provides a menu of options (boolean attribute multiple allows a user to choose more than one option from the list at a time).
<label for="t-shirt">Dropdown:</label> <select id="t-shirt" name="t-shirt">
<option value="">--Please choose an option--</option>
<option value="xs">Extra Small</option>
<option value="s">Small</option>
<option value="m">Medium</option>
<option value="l">Large</option> </select>
Textarea element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text. They have an opening and closing tags, need the cols and rows attribute.
<label for="abstract">Textarea:</label> <textarea id="abstract" name="abstract" row="10" cols="50" placeholder="Comments:"></textarea>
Submit button is an element in HTML that can be used to submit a form (name attribute can be important for processing the form, value is the the text that shows up inside the button).
<input type="submit" name="send" value="Submit">
Other input types:
<input type="color" name="color"/>
<input type="date" name="date"/>
<input type="file" accept="image/*, text/*" name="file"/>
<input id="userId" name="userId" type="hidden" value="abc123">
<input type="month" name="month"/>
<input type="number" name="number"/>
<input type="password" name="password"/>
<input type="range" name="range" min="0" max="25"/>
<input type="search" name="search"/>
<input type="time" name="time"/>
<input type="url" name="url"/>
<input type="tel" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4} required"/>
Form & Input attributes:
video element embeds a media player which supports video playback into the document (uses a src attribute or embedded )
<video width="250" controls autoplay><source src="Blue_Sky_and_Clouds_Timelapse_0892__Videvo.mov" type="video/webm"/></video>
audio element is used to embed sound content in documents (has controls, source, autoplay, muted, loop attributes)
<figure><figcaption>50 cent</figcaption><audio controls src="50_Cent.mp3"></audio></figure>
Canvas element is used to draw graphics on a web page (only a container for graphics, you must use JavaScript to actually draw the graphics)
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d");
SVG (Scalable Vector Graphics) defines vector-based graphics in XML format (used to define graphics for the Web)
<svg width="100" height="100"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow"/></svg>
<svg width="400" height="100"><rect width="400" height="100" style="fill:rgb(68, 199, 223);stroke-width:10;stroke:rgb(0,0,0)"/></svg>
<svg width="400" height="180"><rect x="50" y="20" rx="20" ry="20" width="150" height="150" style="fill:red;stroke:black;stroke-width:5;opacity:0.5"/></svg>
<svg width="300" height="200"><polygon points="100,10 40,198 190,78 10,78 160,198" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;"/></svg>
<em>
Sometimes, you need to draw attention to a particular word or
phrase (italic)
<strong>
Other times you need to strongly emphasize the
importance
of a word or phrase (bold)
HTML markup should provide semantic information about your content (structure of your document), leaving its appearance to CSS.
Line <br>
break produces a line break in text (carriage-return)
<hr>
carries less significance than the separation created by a
new
heading
element, but
more significance than a new paragraph.
<table>
tagThe table header | |
---|---|
The table body | with two columns |
<table>
represents tabular data, information presented in a two-dimensional table
comprised of rows and columns of cells containing data
<caption>
specifies the caption (or title) of a table
<caption>Caption for table</caption>
<thead>
(the table head) defines a set of rows defining the head of the columns of
the table
<tr>
(the table row) defines a row of cells in a table
<th>
(the table header) defines a cell as the header of a group of table cells
<th>The table header</th>
<tbody>
(the table body) encapsulates a set of table rows (tr elements),
indicating that they comprise the body of the table
<td>
(the table data cell) defines a cell of a table that contains data
<td>The table body</td>
@font-face{font-family: "Roboto"; src:url("Roboto-Light-webfont.woff") format("woff");}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?...">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
- Google icons cloud
<i class="material-icons">cloud</i>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- Bootstrap icons
<i class="bi bi-airplane-engines-fill"></i>
<script src="https://kit.fontawesome.com/yourcode.js" crossorigin="anonymous"></script>
- Font Awesome icons
<i class="fas fa-cat"></i>
A CSS "rule" always start
with a "selector" that defines which HTML elements it applies
to. After the
selector, we have the "declarations block" inside of some curly braces. Any
"properties"
we set in here
will affect the selected element. selector{property: value;}
When there's two conflicting properties in a CSS file, the last one is always the one that gets applied.
The same class selector can be applied to multiple elements in a single HTML document.
<link rel="stylesheet" type="text/css" href="styles.css"/>
- linking a CSS
stylesheet
(inside of head)
<style type="text/css">
selector {property: value;}
</style>
- internal style
<tag style="property: value"></tag>
- inline style
/*
CSS "comments */
border-color: var(--color-a);
the var function is used to insert the value of a CSS
variable (have access to the DOM)
The CSS hierarchy for every web page looks like this (ordered from least to most precedence):
Once an element is selected, a property determines the styles that will be applied to that element
* {margin: 0; padding: 0; box-sizing: border-box;}
- universal CSS
selector (*) to override (reset) default stylestop/bottom; left/right
- participates in specifying the vertical / horizontal
position of a positioned element (no effect on non-positioned elements)font-size: 1.2rem;
- sets the size of the fontfont-family: "Helvetica", "Arial", sans-serif;
- defines the typeface
for the element
font-weight: bold;
- defines the "boldness" of the text in an element
font-style: italic;
- indicates whether it's italicized or notfont-stretch: normal/condensed/expanded;
- selects a normal, condensed, or
expanded face from a fontfont-variant: normal;
- allows you to set all the font variants for a font
(font-variant-alternates; font-variant-caps; font-variant-emoji; font-variant-ligatures;
font-variant-numeric; font-variant-position)line-height: 1em;
- determines the number of characters or words that fit into
a
single
line (vertical spacing)text-transform: none;
- specifies how to capitalize an element's text
(capitalize,
uppercase, lowercase)text-decoration: none;
- determines whether text is underlined or not
(text-decoration-color; text-decoration-line; text-decoration-style;
text-decoration-thickness)
text/vertical-align: left;
- defines the horizontal/vertical alignment of the
text (inline, inline-block or table-cell box) (start, end, left, right, center, justify;
baseline, top,
middle, bottom, sub, text-top)text-indent: 1em;
- sets the length of empty space (indentation) that is put
before lines of text in a blockletter/word-spacing;
- sets the horizontal spacing behavior between text
characters/wordswhite-space: normal;
- sets how white space inside an element is
handledtext-overflow: clip/ellipsis;
- sets how hidden overflow content is signaled to
usersword-break: normal;
- sets whether line breaks appear wherever the text would
otherwise overflow its content box (break-all, keep-all, break-word)writing-mode: horizontal-tb;
- sets whether lines of text are laid out
horizontally or vertically, as well as the direction in which blocks progress (vertical-rl,
vertical-lr)text-shadow: 1px 1px 2px red, 0 0 1em blue, 0 0 0.2em blue;
- adds shadows to
textcolumns: 2 auto;
- sets the number of columns to use when drawing an element's
contents, as well as those columns' widths (column count/width; column fill/gap/rule/span)
color: gray;
- color of the foreground (colors the font)background-color: gray;
- colors the backgroundborder-width: thick;
- sets the width of an element's borderborder-style: none;
- sets the line style for all four sides of an element's
border
(dotted, dashed, solid, groove, inset, outset, double, ridge, hidden)border-radius: 50% 20% / 10% 40%;
- rounds the corners of an element's outer
border
edge (border-top-left/right-radius; border-bottom-right/left-radius)border-image: url('/media/examples/border-diamonds.png') 30;
- draws an image around a given element (border-image-outset; border-image-repeat;
border-image-slice; border-image-source; border-image-width)border-collapse: collapse/separate;
- sets whether cells inside a table have
shared or separate bordersbackground-image: url("image.png");
- sets one or more background images on an
elementbackground-position: top;
- sets the initial position for each background image
background-repeat: no-repeat;
- sets how background images are repeated
(repeat,
space, round)background-size: cover
- sets the size of the element's background image (left
to
its natural size, stretched, or constrained to fit the available space - cover)object-fit: none;
- sets how the content of img or video should be resized to
fit its container (contain, cover, fill, scale-down)object-position: right top;
- specifies the alignment of the selected replaced
element's contents within the element's box (top, bottom, left, right, center; percentage /
length / edge offsets values)box-shadow: 10px 5px 5px red;
- adds shadow effects around an element's frame
(offset-x, offset-y, blur-radius, spread-radius, inset and color optionally)filter: blur(5px);
- applies graphical effects like blur or color shift to an
element (blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity,
saturate, sepia)background: linear-gradient(#f69d3c, #3f87a6);
- special type of image that
consists of a progressive transition between two or more colors (linear, radial, repeating,
conic gradient)transform: scale(2, 0.5);
- lets you rotate, scale, skew, or translate an
element (matrix, perspective, rotate, translate, scale, skew)transition: all 1s ease-out;
- allows you to change property values smoothly,
over a given period (transition-property/duration/timing-function/delay)animation: .5s linear 1s infinite alternate slidein;
- allows animation of HTML
elements without using Javascript or Flash
(animation-name/duration/timing-function/delay/iteration-count/direction/fill-mode/play-state/timeline.)
max-width: 50%;
- determines the amount of space between lines in the same
paragraph
(horizontal spacing)list-style-type: none;
- lets you alter the bullet icon used for
list elements (disc, circle, square, decimal, lower/upper-roman, lower/upper-alpha)
box-sizing: border-box/content-box;
- sets how the total width and height of an
element is calculated (border box - padding and border are included in the width and
height)overflow: visible;
- sets the desired behavior when content does not
fit in the parent element box (overflows) in the horizontal and/or vertical
direction (hidden, scroll, auto)margin: 0 auto;
- to horizontally center an element (not have a fixed or absolute
position)cursor: pointer;
- sets the mouse cursor type (pointer)opacity: 0.5;
- sets the opacity of an element (a number in the range 0.0 to 1.0,
or a percentage in the range 0% to 100%)flex: 1 1
- sets how a flex item will grow or shrink to fit the space available in
its flex container (flex-grow, flex-shrink, flex-basis)visibility: visible/hidden/collapse;
- shows or hides an element without changing
the layout of a documentSelectors are used to target the HTML elements on our web pages that we want to style.
Type of selectors:
h1{color: blue;}
- type selectors target an HTML element (follow
the DOM).myclass{font-style: italic;}
- .class selectors target
class attribute on the HTML element <p class="myclass">
(can
be
applied to multiple elements in a single HTML document)
#button{color: #5D6063;}
- #id selectors target
id attribute on the HTML element
<a id="button" href="nowhere.html">Button</a>
(can only have one
element with the same ID per page)
a[href="https://example.com"]{}
- [attribute] selectors give you
different ways to select elements based on
the presence of a certain attribute on an elementa:hover{}
- :pseudo classes style certain states of an element
p::first-line{}
::pseudo elements select a certain part of an
element rather than the element itselfnav a{font-style: normal;}
- descendant selectors let you
target
only those elements that are inside of another elementnav > a{background-color: yellow;}
- child combinator (>)
matches
only
those elements matched by the second selector that are immediate children of elements
matched by the firstimg + p {font-weight: bold;}
- adjacent sibling separates two
selectors and matches the second element only if it immediately follows the first element,
and
both are children of the same parenth1 ~ h2 {color: red;}
- general sibling selects all elements
that
are next siblings of a specified elementWe can select multiple HTML elements in the same CSS rule by separating them with
commas h1, h2, h3, h4, h5, h6{
font-family: "Helvetica";}
The box model is a way to describe how elements are laid out on a web page
padding-(top, right, bottom, left): 2em;
border-(top, right, bottom, left): 1px solid red;
margin-(top, right, bottom, left): 2em;
margin + border + padding + width = actual width
Every element is a box, display affects the layout of neighboring elements.
display:block;
display:inline-block;
display:none;
Behaviors associated with block and inline boxes:
text-align
propertyOverflow sets the desired behavior when content does not fit in the parent element box (overflows) in the horizontal and/or vertical direction
overflow: visible;
overflow: hidden;
overflow: scroll;
overflow: auto;
float: (left,right);
- floats let you put block-level elements
side-by-side instead of on top of each other (reposition elements to the right or left, will not
overlap)
margin: 0 auto;
for center alignment.footer{clear: both;}
- clearing a float is when we tell a block
to
ignore any floats that appear before it (left, right)
.page{overflow: hidden;}
- by adding an overflow: hidden
declaration to a container div, we're telling it to recognize the height of any
floated elements it contains
The "Flexible Box" or "Flexbox" layout mode offers an alternative to Floats for
defining
the overall appearance of a web page. .menu-container {display: flex;}
justify-content: (center, flex-start, flex-end, space-around, space-between);
align-items: (center, flex-start, flex-end, stretch, baseline);
flex-wrap: wrap;
forces items that don't fit to get bumped down to the
next rowflex-direction: (row, column, row-reverse, column-reverse);
"Direction"
refers to whether a container renders its items horizontally or vertically.align-self: (center, flex-start, flex-end, stretch, baseline);
.first-item {order: 1;}
flex: initial;
falls back to the item's explicit width property.A pseudo-class is a keyword added to a selector that specifies a special state of
the selected element (consists of a colon (:)
followed by the pseudo-class
name)
Links:
:link
- A link the user has never visited.
a:link{color: blue; text-decoration: none;}
:visited
- a link the user has visited before.User action:
:hover
- a link with the user's mouse over it.:active
- a link that's being pressed down by a mouse (or finger).:focus
- triggered when the user clicks or taps on an element or selects it with
the keyboardForms:
:enabled
- represents a user interface element that is in an enabled state:checked
- matches when elements such as checkboxes and radio buttons are toggled
on:disabled
- represents a user interface element that is in a disabled state:valid
- matches an element with valid contents:required
- matches when a form element is requiredStructural/Positional:
:first/last-child
- matches an element that is the first/last of its siblings
:nth-child
- uses An+B
notation to select elements from a list of
sibling elements
(A is an integer step size, B is an integer offset, n is all nonnegative integers, starting from
0):only-child
- matches an element that has no siblings:first/last-of-type
- represents the first/last element of its type among a group
of sibling elements:only-of-type
- matches an element that has no siblings of the chosen type selector
A pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element
::first-letter
- applies styles to the first letter of the first line of a
block-level element::first-line
- applies styles to the first line of a block-level element::before/after
- creates a pseudo-element that is the first/last child of the
selected element::selection
- applies styles to the part of a document that has been highlighted by
the userThe CSS position property sets how an element is positioned in a document.
position: relative; top: 30px; left: 30px;
position: absolute; top: 10px; left: 10px;
position: fixed; bottom: 0; right: 0;
Grid CSS property is a shorthand property that sets all of the explicit and implicit grid properties
in a single declaration grid: repeat(3, 80px) / auto-flow;
Using grid you specify one axis using grid-template-rows or grid-template-columns, you then specify how content should auto-repeat in the other axis using the implicit grid properties: grid-auto-rows, grid-auto-columns, and grid-auto-flow
grid-template-rows: auto;
- defines the line names and track sizing functions of
the grid rows (horizontal track in a CSS Grid Layout, that is the space between two horizontal
grid lines)grid-template-columns: 1fr 2fr;
- defines the line names and track sizing functions
of
the grid columns (vertical track in a CSS Grid Layout, that is the space between two
vertical grid lines)grid-auto-rows: minmax(30px, auto);
- specifies the size of an implicitly-created
grid row track (space between two adjacent grid lines) or pattern of tracksgrid-auto-columns: min-content;
- specifies the size of an implicitly-created
grid column track or pattern of tracksgrid-auto-flow: row;
- controls how the auto-placement algorithm works, specifying
exactly how auto-placed items get flowed into the grid"Responsive design" refers to the idea that your website should display equally well in everything from widescreen monitors to mobile phones.
@media only screen and (max-width: 400px) {
@media only screen and (min-width: 401px) and (max-width: 960px) {
@media only screen and (min-width: 961px) {
@media only screen and (orientation: landscape) {
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
-
disabling viewport zoomingh1{font-size: 1.2em}
- 20% greater than the computed font size inherited by h1
elements
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
<div class="container"><div class="row"><div class="col-xs-12">
layout is based on a 12 column grid, every grid consists of a
container, a
row
and one or more column classes
class="container-md"
- container is a class used to wrap and
center the content within a fixed width (container sets a max-width at each
responsive
breakpoint; container-{sm, md, lg, xl, xxl} width: 100% until the specified
breakpoint; container-fluid width: 100% at all breakpoints)class="col-sm-3"
the class col-xx-yy always
starts with "col"; xx component is the viewport size: xs, sm, md, lg;
yy component is the number of columns 0..12
class="text-warning bg-dark"
- colors (primary, sucess,
danger, warning, dark...); bg - backgroundclass="d-inline"
- display properties are used to control the
visibility of
the HTML elements on the viewport (none, inline, inline-block, block, grid, inline-grid,
table, table-cell, table-row, flex, inline-flex)class="img-fluid"
- images are made responsive with .img-fluid
(applies
max-width: 100%;
and height: auto;
to the image so that it scales
with the parent width)
class="btn btn-primary"
- buttons class sets up basic
styles such as padding and content alignment of button (can be used on a or
input elements)
m
or padding
p
values to an element
or a subset of its sides with shorthand classes (sides: t-top; b-bottom;
s-start; e-end;
x-left+right; y-top+bottom; size: 0, 1, 2 ..5, auto)
JavaScript is a programming language that adds interactivity to your website (client-side script, meaning the browser processes the code instead of the web server).
Read and write HTML elements, reacts to events, validate data, detect the visitor's browser, create cookies
<script type="text/javascript" src="scripts/main.js"></script>
- linking a
JS script (inside of
head)
/*
Everything in between is a comment */
// This is a comment
JavaScript doesn't have a built-in print function, data is displayed via:
alert("Hello world!");
const aNumber = Number(window.prompt("Type a number", ""));
document.write("<h1>Time to learn JavaScript</h1>");
element.innerHTML = “Time to learn JavaScript ”;
console.log(“Leave a secret message”);
Programming interface for web documents (represents the page that programs can change the document structure, style, and content).
Data types being passed around the API:
document.querySelectorAll()
. Items are accessed: list.item(1)
,
list[1]
Most commonly-used interfaces in the DOM:
document.getElementById("one")
- will go into your document and look for that
specific elementdocument.getElementsByTagName("p")
- will give you all the elements with a
particular tag name in a collectiondocument.getElementsByClassName("blue")
- will get all elements that match a
particular classdocument.querySelector("#special .myclass")
- returns the first Element within the
document that matches the specified selector, or group of selectorsdocument.querySelectorAll("#special p")
- returns a static NodeList representing a
list of the document's elements that match the specified group of selectorsdocument.createElement("p")
- creates the HTML element specified by tagNamedocument.createTextNode("paragraph")
- put text in elementElement.innerHTML
- gets or sets the HTML or XML markup contained within the
elementElement.className
- allows you to set the class, or classes for an elementElement.classList
- read-only property that returns a live DOMTokenList collection
of the class attributes of the elementElement.setAttribute("name", "helloButton")
- sets the value of an attribute on the
specified elementElement.getAttribute("id")
- returns the value of a specified attribute on the
elementElement.removeAttribute("align")
- removes the attribute with the specified name
from the elementElement.getBoundingClientRect()
- returns a DOMRect object providing information
about the size of an element and its position relative to the viewport.Element.focus()
- sets focus on the specified element, if it can be focused
document.getElementById("myTextField").focus()
EventTarget.addEventListener()
- sets up a function that will be called whenever
the specified event is delivered to the targetHTMLElement.style
- returns the inline style of an element in the form of a live
CSSStyleDeclaration object that contains a list of all styles properties for that element
.style.display="none";
Node.appendChild()
- adds a node to the end of the list of children of a specified
parent nodeNode.removeChild()
- removes a child node from the DOM and returns the removed node
Node.textContent
- represents the text content of the node and its descendants
let text = document.getElementById("divA").textContent;
Node.parentNode
- returns the parent of the specified node in the DOM tree
window.onload
- is fired when the whole page has loaded, including all dependent
resources such as stylesheets, scripts, iframes, and imageswindow.scrollTo({top: 0, left: 0, behavior: "smooth"})
- scrolls to a particular
set of coordinates in the documentwindow.scrollY / scrollX
- returns the number of pixels that the document is
currently
scrolled vertically / horizontally (same as pageYOffset / pageXOffset)window.scrollBy()
- scrolls the document in the window by the given amountsetInterval(func, delay, arg1, arg2, …argN)
- repeatedly calls a function or
executes a code snippet, with a fixed time delay between each callsetTimeout(functionRef, delay, param1, param2, …paramN)
- sets a timer which
executes a function or specified piece of code once the timer expireslocation.reload()
- reloading the current pageIstance properties of the DOMTokenList (set of space-separated tokens):
const paragraphs = document.querySelectorAll("p").length;
const paragraphs = document.querySelectorAll("p").value;
Istance methods of the DOMTokenList:
add(token1, token2, /* …, */ tokenN)
contains(token)
tokenList.item(index)
remove(token1, token2, /* …, */ tokenN)
replace(oldToken, newToken)
toggle(token)
Javascript can listen for events and handle them when they occur (the listener listens out for the event happening, and the handler is the code that is run in response to it happening).
addEventListener("click", function());
- recommended method for adding event handlers
event object - parameter inside an event handler function to provide extra features and information (event / evt/ e)
preventDefault()
- method that prevent an event from doing what it does by default
A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence
var
- the only way to declare variables when JavaScript was first created
(confusing and error-prone, var hoisting)let
- declares re-assignable, block-scoped local variables,
optionally initializing each to a valueconst
- declares block-scoped local variables (cannot be redeclared by any other
declaration in the same scope)length
- contains the length of the string in UTF-16 code units
str.length;
concat()
- concatenates the string arguments to this string and returns a
new string str1.concat(" ", str2);
charAt()
- returns a new string consisting of the single UTF-16 code unit
at the given index sentence.charAt(4);
endsWith()
- determines whether a string ends with the characters of this
string, returning true or false as appropriate str1.endsWith("best!");
indexOf()
- searches this string and returns the index of the first
occurrence of the specified substring paragraph.indexOf("dog");
lastIndexOf()
- searches this string and returns the index of the last
occurrence of the specified substring paragraph.lastIndexOf("dog");
match()
- retrieves the result of matching this string against a regular
expression paragraph.match(/[A-Z]/g);
replace()
- returns a new string with one, some, or all matches of a
pattern replaced by a replacement (pattern can be a string or a RegExp, and the
replacement can be a string or a function called for each match)replaceAll()
- returns a new string with all matches of a pattern replaced
by a replacement p.replaceAll("dog", "monkey");
search()
- executes a search for a match between a regular expression and
this string, returning the index of the first match in the stringslice()
- extracts a section of this string and returns it as a new string,
without modifying the original string str.slice(4, 19);
split()
- takes a pattern and divides this string into an ordered list of
substrings by searching for the pattern, puts these substrings into an array, and
returns the array str.split(" ");
startsWith()
- determines whether this string begins with the characters of
a specified string, returning true or false as appropriate
str1.startsWith("Sat");
substring()
- returns the part of this string from the start index up to
and excluding the end index, or to the end of the string if no end index is supplied
str.substring(1, 3);
toString()
- returns this string value stringObj.toString();
trim()
- removes whitespace from both ends of this string and returns a new
string, without modifying the original string (trimStart or trimEnd for just one end)
length
- represents the number of elements in that arraysort()
- sorts the elements of an array in place and returns the reference
to the same array, now sortedpush()
- adds the specified elements to the end of an array and returns the
new length of the arraypop()
- removes the last element from an array and returns that element
join()
- creates and returns a new string by concatenating all of the
elements in this array, separated by commas or a specified separator stringtoString()
- returns a string representing the specified array and its
elementsvalues()
- returns a new array iterator object that iterates the value of
each item in the arrayforEach()
- executes a provided function once for each array elementmap()
- creates a new array populated with the results of calling a
provided function on every element in the calling arrayreduce()
- executes a user-supplied "reducer" callback function on each
element of the array, in order, passing in the return value from the calculation on the
preceding elementsplice()
- changes the contents of an array by removing or replacing
existing elements and/or adding new elements in placeindexOf()
- returns the first index at which a given element can be found
in the array, or -1 if it is not presentfor (i = 0; i < array.length; i++){...}
const person = {name:["Bob","Smith"], age:32, intr(){console.log(`I'm ${this.name[0]}`);};
person.age;
- access the object's properties and methods using dot
notationperson.["name"][0];
- or using use square bracketsperson.age = 45;
- set (update) the value of object membersconst myDataName = "height"; const myDataValue = "1.75m"; person[myDataName] = myDataValue;
- set the value of member namesthis
keyword refers to the current object the code is being written inside
(person)function Person(name){this.name = name; console.log(`I'm ${this.name}`);};} const joe = new Person("Joe");
- A constructor is just a function called using the new keywordthis
, []
, {}
, function
,
class
, function*
new
, super
i++
postfix increment, i--
postfix decrement,
++i
prefix increment, --i
prefix decrement
delete
,
void
, typeof
, ~
bitwise not, !
logical not
**
exponentiation, *
multiplication,
/
division, %
remainder, +
addition, -
subtraction
<
less then, >
greater then,
<=
less then or equal, >=
greater then or equal,
istanceof
, in
==
equality,
!=
inequality, ===
strict equality, !==
strict inequality
<<
bitwise left shift, >>
bitwise right shift,
>>>
bitwise unsigned right shift
&
AND, |
OR,
^
XOR
&&
logical AND, ||
logical OR,
??
nullish coalescing
(condition ? ifTrue : ifFalse)
=
assignment, *=
multiplication assignment, /=
division, %=
remainder, +=
addition, -=
subtractionx = (2, 3); console.log(x); //3
for (let i = 0; i < 9; i++){str = str + i;}
for (const property in object) {console.log(`${property}: ${object[property]}`);}
for (const element of array1){console.log(element);}
if (x > 50){...} else if (x > 5){...} else{...}
while (n < 3){n++;}
Functions are bits of codes that you can reuse (block of code designed to perform a particular task)
function name(parameter){...}
- defined with the function keyword,
followed by
a name, followed by parentheses ( )const x = function(y){return y * y;};
function makeUpperCase(aString){return aString.toUpperCase();}
- function
declarationconst makeUpperCase = (aString) => {return aString.toUpperCase()};
- make
function
expression, remove the word "function" and add an "arrow"const makeUpperCase = aString => {return aString.toUpperCase();}
- remove the
parentheses if there is only one parameterconst makeUpperCase = aString => aString.toUpperCase();
- remove the curly
braces and the return keyword if you have just one statement and it is a return statement
(function(){})();
(() => {})();
function random(min, max){return Math.floor(Math.random() * (max - min + 1)) + min;}
- returns a random number in the range between the two numbersfunction randomRGB(){return `rgb(${random(0, 255)},${random(0, 255)},${random(0, 255)})`;}
- generates a random color represented as an rgb() stringclass Person {name; constructor(name){this.name = name;} intr(){console.log(`I'm ${this.name}`);}}
this is a keyword that allows an element to reference itself (allows to access an element's info, is also used outside functions)
menuLinks.addEventListener("click", function(){console.log(this.innerHTML);});
JS only has one construct: objects, each object has a private property which holds a link to another object called its prototype
function iPhone(){};
- constructor
iPhone.prototype.faceID = function(){...};
- a method for recognizing faces
let myPhone = new iPhone(); myPhone.faceId();
myPhone.faceID = undefined;
- deleting a feature
__proto__
is an object in every class instance that points to the prototype it was
created from. Only true difference between prototype and __proto__ is that the former is a
property of a class constructor, while the latter is a property of a class instance.Object.assign()
- copies all enumerable own properties from one or more source
objects to a target objectObject.create()
- creates a new object, using an existing object as the prototype
of the newly created objectObject.keys()
- returns an array of a given object's own enumerable string-keyed
property namesObject.values()
- returns an array of a given object's own enumerable string-keyed
property valuesObject.hasOwn()
- returns true if the specified object has the indicated property
as its own propertyare patterns used to match character combinations in strings (in JS regular expressions are also objects)
const re = /ab+c/;
- construct a regular expression using a regular expression
literal (pattern enclosed between slashes)const re = new RegExp("ab+c");
- calling the constructor function of the RegExp
object (when you know the pattern will be changing or you don't know the
pattern - getting it from another source)The RegExp object is used for matching text with a pattern
exec()
- executes a search with this regular expression for a match in a specified
string and returns a result array, or nulltest()
- executes a search with this regular expression for a match between a
regular expression and a specified stringjQuery was originally created by John Resig in 2006 and became the most popular JavaScript library (jQuery is just more JavaScript, but it makes doing some things a bit easier).
JQuery object is created with $()
or JQuery()
<script src="jquery-3.7.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
jQuery syntax - methods (API documentation)
$("p").css("color","red");
- css is one of the very many jQuery
methods (takes
two inputs, a property - color and a value - red)$("li:contains(three)").css("border", "solid 2px violet");
contains - select all elements that contain the specified text
$("a").click(function(){alert($(this).html());});
- html method
in jQuery will
give you back the html, just like innerHTML$("a").click(function(){alert(this.innerHTML);});
- you can still just mix in plain
old JavaScript as well.hide() / .show();
- hide or show the
matched elements (hide is equivalent to
calling .css("display", "none")
).slideUp() / .slideDown();
- hide or show the matched elements with a
sliding motion $("#box").slideUp("slow");
.fadeIn() / .fadeOut();
- display or hide the matched elements by
fading them to opaque / transparent $("#box").fadeOut(3000);
.animate();
- perform a custom animation of a set of
CSS properties
$("#box").animate({width: "710px", fontSize: "24px", left: "+=300px"});
$("li.third-item").next();
next
- get the immediately following sibling of each element in the set of matched elements .toggle();
toggle - display or hide the matched
elements.attr();
attr - get the value of an attribute for
the first element in the set of matched elements or set one or more attributes for every matched
element.on('load', function(){};
on - attach an event handler
function for one or more events to the selected elements (load, scroll).load("ajax/test.html");
load - load data from the
server and place the returned HTML into the matched elements.clone().appendTo(".goodbye");
clone - create a deep
copy of the set of matched elements$("li").first().css("background-color", "red");
first / last -
Reduce the set of matched elements to the first / last in the set.remove();
remove - remove the set of matched
elements from the DOM.is(selector, function, selection, elements)
is - check the
current matched set of elements against a
selector, element, or jQuery object and return true if at least one of these elements matches
the given arguments.offset()
offset - get the current coordinates of
the first
element, or set the coordinates of every element, in the set of matched elements, relative to
the document (returns an object containing the properties top and left).each(function)
each - iterate over a jQuery object,
executing a function for each matched element.height()
height - get the current computed height
for the first element in the set of matched elements or set the height of every matched element
.scrollTop()
scrollTop - get the current vertical
position of
the scroll bar for the first element in the set of matched elements or set the vertical position
of the scroll bar for every matched element.eq(index)
eq - reduce the set of matched elements to the one at
the specified index $("li").eq(2).css("background-color", "red");
.serialize()
serialize - encode a set of form elements
as a string for submission$.ajax()
ajax - perform an asynchronous HTTP (Ajax) request<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script>
- A jQuery plugin from GSGD to give advanced easing options
first used in 2005 to describe a group of technologies that come together to make doing tasks asynchronously with JavaScript possible
Ajax's most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page
Early on, Ajax relied heavily on the XMLHttpRequest web API to asynchronously get data from the server, or send data to a server
const httpRequest = new XMLHttpRequest();
- make an HTTP request to the
server with JavaScript (instance of an object with the necessary functionality)readyState
- returns the state an XMLHttpRequest client is in (0
UNSENT; 1
OPENED; 2 HEADERS_RECEIVED; 3 LOADING; 4 DONE)responseText
- returns the text received from a server following a
request
being sentresponse
- returns the response's body content as an ArrayBuffer, a
Blob, a
Document, a JavaScript Object, or a stringstatus
- returns the numerical HTTP status code of the XMLHttpRequest's
response (UNSENT/OPENED: 0; LOADING/DONE: 200)abort()
- aborts the request if it has already been sent (its
readyState is
changed to XMLHttpRequest.UNSENT(0) and the request's status code is set to 0)open()
- initializes a newly-created request, or re-initializes an
existing one
httpRequest.open("GET", "http://www.example.org/some.file", true);
send()
- sends the request to the server
httpRequest.send(null);
readystatechange
event is fired whenever the readyState property of the
XMLHttpRequest changes
httpRequest.onreadystatechange=()=>{//process the server response here.};
jQuery uses ajax method to get the data from an external URL
$.ajax({url: "https://www.example.org/some.file", cache: false}).done(function(){});
modern replacement for the older XMLHttpRequest object, returns a promise, which will resolve to either success or failure
fetch()
- starts the process of fetching a resource from the network, returning a
promise which is fulfilled once the response is availableHeaders
- allows you to perform various actions on HTTP request and response
headers const myHeaders = new Headers();
Request
- represents a resource request
const myRequest = new Request("https://www.mozilla.org/favicon.ico");
url
- contains the URL of the request const myURL = myRequest.url;
method
- contains the request's method (GET, POST, etc.)
const myMethod = myRequest.method;
text()
- reads the request body and returns it as a promise that resolves with
a String myRequest.text().then((text) => {});
json()
- reads the request body and returns it as a promise that resolves with
the result of parsing the body text as JSONResponse
- represents the response to a requestFormData()
- provides a way to construct a set of key/value pairs representing form
fields and their values, which can be sent using the fetch, XMLHttpRequest.send or
navigator.sendBeacon method
append()
- appends a new value onto an existing key inside a FormData object, or
adds the key if it does not already existdelete()
- deletes a key and its value(s) from a FormData objectentries()
- returns an iterator which iterates through all key/value pairs
contained in the FormDataget()
- returns the first value associated with a given key from within a FormData
objecthas()
- returns whether a FormData object contains a certain keykeys()
- returns an iterator which iterates through all keys contained in the
FormDataset()
- sets a new value for an existing key inside a FormData object, or adds the
key/value if it does not already existvalues()
- returns an iterator which iterates through all values contained in the
FormDatarepresents the eventual completion (or failure) of an asynchronous operation and its resulting value
Promise
is in one of these states:were added to JavaScript with ES2017 as a way of making it easier to work with the fetch API and promises
async
function declaration creates a binding of a new async function to a given
nameawait
operator is used to wait for a Promise and get its fulfillment value (can
only be used inside an async function or at the top level of a module)text-based data format following JavaScript object syntax (exists as a string — useful when you want to transmit data across a network), which was popularized by Douglas Crockford
const json = '{"name":"Joe", "age":23}';
- requires double quotes
to be
used around
strings and property names
const obj = JSON.parse(json);
- JSON.parse() parses a JSON string,
constructing the JavaScript value or object described by the string
console.log(obj.name);
- access the data inside it using the
dot/bracket notation
var data = JSON.stringify(obj);
- JSON.stringify() converts a
JavaScript value to a JSON string
wraps pieces of information in tags, similar to HTML, but the names of the tags are user-defined (grouping of information is done by nesting the tags within each other)