HTML - HyperText Markup Language

HTML Basics

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

  • No one “runs” the Internet or the Web, some groups do take proactive roles:
    • Internet Engineering Task Force (IETF)
    • World Wide Web Consortium (W3C)
    • The Web Accessibility Initiative (WAI)
  • Evolution of HTML:
    • 1993 HTML 1.0 - Developed by Tim Berners-Lee to link document
    • 1995 HTML 2.0 - Developed by Internet Engineering Task Force RFC to include stylized text and tables
    • 1996 CSS 1
    • 1997 HTML 3.2 - Developed by W3C and included browser specific features
    • 1997 HTML 4.0 - A move back to normalizing the pages across platforms
    • 1998 CSS 2
    • 1999 HTML 4.01 - Introduced different document types
    • 2012 HTML 5 - Back to HTML plus multimedia and semantic tags

<!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:

  • Use unique title and description tags for each page
  • Use relevant keywords in your meta tags
  • Keep your meta tags concise and relevant
  • Avoid using too many meta tags
  • Use viewport tags to ensure your website is displayed correctly on different devices

Basic elements

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).

  • id attribute - identifies an element
  • class attribute - classifies an element
  • src attribute - specifies a source for embeddable content
  • href attribute - provides a hyperlink reference to a linked resource

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:

  • bold tag - used to draw the reader's attention to the element's contents, which are not otherwise granted special importance <b>bold tag</b>
  • italic tag - represents a range of text that is set off from the normal text for some reason<i>italic tag</i>
  • underline tag - represents a span of inline text which should be rendered by default as a simple solid underline, but may be altered using CSS <u>underline tag</u>
  • strikethrough tag - renders text with a strikethrough, or a line through it <s>strikethrough tag</s>
  • inserted tag - represents a range of text that has been added to a document <ins>inserted tag</ins>
  • superscript tag - specifies inline text which is to be displayed as superscript for solely typographical reasons <sup>tag</sup>
  • subscript tag - specifies inline text which should be displayed as subscript for solely typographical reasons <sub>tag</sub>
  • small tag -represents side-comments and small print, like copyright and legal text, independent of its styled presentation <small>small tag</small>
  • mark tag - represents text which is marked or highlighted for reference or notation purposes <mark>mark tag</mark>
  • del tag - defines text that has been deleted from a document <del>del tag</del>

iframe tag - used to embed another document (google map, youtube) <iframe>tag</iframe>

  • creating a separate section or page
  • displaying adds
  • creating an image gallery or slideshow
  • embedding social media feeds

Headings <H1> define the outline of the site, have syntax and semantics

H2 Headings

H3 Headings

H4 Headings

H5 Headings
H6 Headings

Useful elements

  • <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 70%
  • <details> creates a disclosure widget in which information is visible only when the widget is toggled into an open state
    DetailsSomething small enough to escape casual notice.
  • <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)
  • 65%

Lists

List element is used to create lists of items on a webpage

Unordered <ul> list

  • add a "ul" element (it stands for unordered list)
  • add each item in its own <li> element
  • intended for items that relate, but do not need to be in a particular order

Ordered <ol> list

  1. ordered list item elements <li> are the same (can be numerical or alphabetical)
  2. the numbers increment on their own
  3. for items that need to be ordered for a reason

Description <dl> list

use <dt> instead of <li>
use <dd> for indentation

Styling lists

  • list-style-type - sets the marker (such as a disc, character, or custom counter style) of a list item element
  • list-style-image: url("image.gif"); - sets an image to be used as the list item marker
  • list-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 once

Images

Image content is defined outside of the web page that renders it, included in web pages with the <img> tag and its src attribute

  • alt attributes define a “text alternative” to the image being displayed (info for screen readers, broken links)
  • title displays on hover

<img src="images/mochi.jpg" alt="description" title="title"/>

  • JPG - designed for handling large color palettes without exorbitantly increasing file size
  • GIF - go-to option for simple animations, never use them for photos
  • PNG - great for anything that's not a photo or animated, excellent fit for icons, technical diagrams, logos
  • SVG - vector-based graphics format, meaning it can scale up or down to any dimension without loss of quality
  • description

Forms

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/>

  • action attribute defines the URL that processes the form (where the page should send the information ).
  • method attribute tells the form how to send the data from the form (can be either post or get)
  • length property returns the number of controls in the form element
  • elements property returns an HTMLFormControlsCollection listing all the form controls contained in the form element
  • name property represents the name of the current form element as a string (how the data is going to get to the server)
  • target property interface represents the target of the form's action (the frame in which to render its output)

Input element is used to create interactive controls for web-based forms in order to accept data from the user. <label> give the input tag a label, for attribute in the label tag connects the label to the input tag (matches the value in the ID attribute).

<label for="full-name">Input form:</label> <input id="full-name" name="full-name" type="text" placeholder="Enter your name"/>

Email input element (type = email) is used to let the user enter and edit an email address.

<label for="email">Email:</label> <input id="email" name="email" type="email" placeholder="joe@example.com"/>

Radio buttons are an easy way to allow users to make a quick choice from a small list of options (permit users to select one option only). It is considered better practice to put the label after the input element.

Options:
  • Be wrapped in a <fieldset>, which is labeled with a <legend>
  • Associate a <label> element with each radio button.
  • Use the same name attribute for each radio button in the group.
  • Use different value attributes for each radio button.

<fieldset class="legacy-form-row"><legend'>Options:</legend> <input id="talk-type-1" name="talk-type" type="radio" value="main-stage"/> <label for="talk-type-1" class="radio-label">Option 1</label> input id="talk-type-2" name="talk-type" type="radio" value="workshop" checked/> <label for="talk-type-2" class="radio-label">Option 2</label> <fieldset/>

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:

  • color - opening a color picker when active in supporting browsers <input type="color" name="color"/>
  • date, datetime-local - opens a date picker or numeric wheels for year, month, day / date and time <input type="date" name="date"/>
  • file - lets the user select a file <input type="file" accept="image/*, text/*" name="file"/>
  • hidden - not displayed but whose value is submitted to the server <input id="userId" name="userId" type="hidden" value="abc123">
  • month - control for entering a month and year, with no time zone <input type="month" name="month"/>
  • number - displays a spinner and adds default validation <input type="number" name="number"/>
  • password - single line text field whose value is obscured (will alert user if site is not secure) <input type="password" name="password"/>
  • range - displays as a range widget defaulting to the middle value <input type="range" name="range" min="0" max="25"/>
  • search - single-line text field for entering search strings <input type="search" name="search"/>
  • time - control for entering a time value with no time zone <input type="time" name="time"/>
  • url - field for entering a URL <input type="url" name="url"/>
  • tel - used to let the user enter and edit a telephone number <input type="tel" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4} required"/>

Form & Input attributes:

  • name - name of the form control, submitted with the form as part of a name/value pair (provide a unique identifier for the input field)
  • value - the initial value of the control
  • type - type of form control
  • disabled - turns off an element or control so that it is not available for interaction or input
  • placeholder - provides a brief hint to the user as to what kind of information is expected in the field (disappears once the control is clicked in or gains focus)
  • required - enforces that an element or form control must contain a value upon being submitted to the server
  • autocomplete - takes as its value a space-separated string that describes what, if any, type of autocomplete functionality the input should provide
  • checked - indicates that the radio button or checkbox is the currently selected
  • max, min - defines the greatest / most negative value in the range of permitted values
  • maxlength, minlength - defines the maximum / minimum string length (measured in UTF-16 code units) that the user can enter into the field
  • pattern - defines a regular expression that the input's value must match in order for the value to pass constraint validation

Video & Audio

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)

50 cent

<figure><figcaption>50 cent</figcaption><audio controls src="50_Cent.mp3"></audio></figure>

Canvas, SVG

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>

  • always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas, to add a border, use the style attribute.
  • canvas is a rectangular area on an HTML page, by default, a canvas has no border and no content.
  • to draw the graphics: 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>

Inline (strong, emphasized) elements

<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)

Structure vs presentation

HTML markup should provide semantic information about your content (structure of your document), leaving its appearance to CSS.

Empty elements

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 <table> tag

Caption for table
The 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>

Typography

  • Download a web font and add it to your project (fontsquirrel).
  • Embed the web font in your stylesheet.
  • @font-face{font-family: "Roboto"; src:url("Roboto-Light-webfont.woff") format("woff");}
  • Use the font elsewhere in your stylesheet.
  • Externally hosted web fonts (fonts.google). <link rel="stylesheet" href="https://fonts.googleapis.com/css?...">
  • Add the name of the icon class to any inline HTML element to insert a icon (The i and span elements are widely used to add icons)
    • <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>
CSS - Cascading Style Sheets

CSS Basics

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):

  • The browser's default stylesheet
  • User-defined stylesheets
  • External stylesheets
  • Page-specific styles - The style element always lives in the head of a web page
  • Inline styles - CSS rules in the style attribute of an HTML element

Properties

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 styles
  • top/bottom; left/right - participates in specifying the vertical / horizontal position of a positioned element (no effect on non-positioned elements)
  • fonts and text properties:
    • font-size: 1.2rem; - sets the size of the font
    • font-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 not
    • font-stretch: normal/condensed/expanded; - selects a normal, condensed, or expanded face from a font
    • font-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 block
    • letter/word-spacing; - sets the horizontal spacing behavior between text characters/words
    • white-space: normal; - sets how white space inside an element is handled
    • text-overflow: clip/ellipsis; - sets how hidden overflow content is signaled to users
    • word-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 text
    • columns: 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 background
  • border properties:
    • border-width: thick; - sets the width of an element's border
    • border-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 borders
  • image properties:
    • background-image: url("image.png"); - sets one or more background images on an element
    • background-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 document

Selectors

Selectors 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 element
  • a: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 itself
  • Combinators - combine other selectors in order to target elements within our documents
    • nav a{font-style: normal;} - descendant selectors let you target only those elements that are inside of another element
    • nav > a{background-color: yellow;} - child combinator (>) matches only those elements matched by the second selector that are immediate children of elements matched by the first
    • img + 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 parent
    • h1 ~ h2 {color: red;} - general sibling selects all elements that are next siblings of a specified element

We can select multiple HTML elements in the same CSS rule by separating them with commas h1, h2, h3, h4, h5, h6{ font-family: "Helvetica";}

CSS box model

The box model is a way to describe how elements are laid out on a web page

  • Content - The text, image, or other media content in the element
  • Padding - The space between the box's content and its border (positive - border moves outward from element, negative - border moves over the element). padding-(top, right, bottom, left): 2em;
  • Border - The line between the box's padding and margin (define the stroke width of the border, then its style, followed by its color). border-(top, right, bottom, left): 1px solid red;
    • any element can have a border around it
    • border property specifies style, width, and color
    • the border style MUST be specified (dotted, dashed, solid, groove, inset, outset, double, ridge, hidden)
  • Margin - The space between the box and surrounding boxes (positive - element moves right/down, negative - element moves left/upward) margin-(top, right, bottom, left): 2em;
    • when one value is specified, it applies the same margin to all four sides
    • when two values are specified, the first margin applies to the top and bottom, the second to the left and right
    • when three values are specified, the first margin applies to the top, the second to the right and left, the third to the bottom
    • when four values are specified, the margins apply to the top, right, bottom, and left in that order (clockwise)

margin + border + padding + width = actual width

Display

Every element is a box, display affects the layout of neighboring elements.

  • inline sits next to other elements (takes up "just enough" width and height)
  • block forces line break (default: take up all horizontal width and "just enough" height)display:block;
  • inline-block same as inline, but accepts height and width display:inline-block;
  • none makes an element completely disappear (Still in DOM, but not visual) display:none;

Behaviors associated with block and inline boxes:

  • Block boxes always appear below the previous block element (static flow).
  • Width of block boxes is set automatically based on the width of its parent container.
  • Default height of block boxes is based on the content it contains.
  • Inline boxes don't affect vertical spacing (completely ignore the top and bottom margins of an element).
  • Width of inline boxes is based on the content it contains, not the width of the parent element.
  • Inline boxes are aligned with the text-align property

Overflow sets the desired behavior when content does not fit in the parent element box (overflows) in the horizontal and/or vertical direction

  • visible - can cause text to show up “on top” of other text overflow: visible;
  • hidden - hides anything that goes beyond bounding box overflow: hidden;
  • scroll - gives horizontal and vertical scrollbars overflow: scroll;
  • auto - adds scrollbars as needed overflow: auto;

Floats

  • Block elements always appeared vertically one after another, effectively limiting us to a single-column layout
  • 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

Flexbox

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;}

  • The job of a flex container is to group a bunch of flex items together and define how they're positioned (position elements that are one level deep).
  • Every HTML element that's a direct child of a flex container is an "item".
  • Horizontal alignment of the items: justify-content: (center, flex-start, flex-end, space-around, space-between);
  • Vertical alignment of the items: 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 row
  • flex-direction: (row, column, row-reverse, column-reverse); "Direction" refers to whether a container renders its items horizontally or vertically.
  • Flex item (individual item) alignment: align-self: (center, flex-start, flex-end, stretch, baseline);
  • Order property to a flex item: .first-item {order: 1;}
  • flex: initial; falls back to the item's explicit width property.
  • auto-margins - "divider" for flex items in the same container (eat up all the extra space in a flex container).

Pseudo classes

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 keyboard

Forms:

  • :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 required

Structural/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 user

Position property

The CSS position property sets how an element is positioned in a document.

  • Static position is default value
    • default value for elements
    • place in the next available position
    • not affected by the top, bottom, left, and right properties
  • Relative positioning moves elements around relative to where they would normally appear in the static flow of the page. position: relative; top: 30px; left: 30px;
    • positioned "relative to itself"
    • take the static position, but add offsets
    • the new positioning does NOT affect any other element (it is possible to move an element and leave a big hole where it would have been)
    • relatively positioned elements are often used as container blocks for absolutely positioned elements
  • Absolute positioning is just like relative positioning, but the offset is relative to the entire browser window instead of the original position of the element. position: absolute; top: 10px; left: 10px;
    • element is removed from the document flow and positioned relative to it's nearest ancestor (or the root)
    • other elements behave as if element does not exist
    • can end up on top of another element
  • Fixed positioning has a lot in common with absolute positioning, difference is that fixed elements don't scroll with the rest of the page. position: fixed; bottom: 0; right: 0;
    • positioned relative to the browser window
    • will not move, even if the window is scrolled
    • think of popup boxes that won't go away, or a navigation bar that is always visible on the top
  • Sticky positioning "sticks" element to its nearest ancestor that has a "scrolling mechanism"
  • The z-index property lets you control the depth of elements on the page (negative z-index values go farther into the page, and positive ones come out of the page).
    • element above or below overlapping elements
    • multiple elements may be placed in the same position
    • z-index is a numeric value, positive or negative that dictates stacking order

Grid

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 tracks
  • grid-auto-columns: min-content; - specifies the size of an implicitly-created grid column track or pattern of tracks
  • grid-auto-flow: row; - controls how the auto-placement algorithm works, specifying exactly how auto-placed items get flowed into the grid

Responsive design

"Responsive design" refers to the idea that your website should display equally well in everything from widescreen monitors to mobile phones.

  • Media queries allow the style to depend upon the media properties.
    • @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) {
    • you should have min-width instead of max-width
  • A fluid layout is one that stretches and shrinks to fill the width of the screen
    • your content should fit the size constraints of the viewport.
    • vertical scrolling is about content, horizontal scrolling is bad design.
  • A fixed-width layout is the opposite: it has the same width regardless of the screen dimensions
  • <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/> - disabling viewport zooming
  • Relative measurements - relative length units specify a length relative to another length
    • child elements do not inherit the relative values as specified for their parent; they inherit the computed values.
    • em unit - equal to the computed value of the font-size property of the element on which it is used, h1{font-size: 1.2em} - 20% greater than the computed font size inherited by h1 elements
    • percentages are resizeable units for font size, and their CSS declarations can be inherited (similar to em's)
    • rem unit - its value is relative to the root element of the document and not to any other elements associated to it (16px - default font size of root element)
  • Bootstrap framework for creating web sites; focuses on responsive, mobile-first approach; consists of CSS and HTML templates, JavaScript extensions
    • <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>
    • 12-column grid system (Helps with spacing issues, built-in responsive design)
    • common jQuery functionalities (Accordion, Drop-down menus, Carousel)
    • familiar “look and feel” (Many sites use Bootstrap, makes your forms look “legitimate”)
    • hardcodes the breakpoints for different viewports: xs- extra small (480px), sm- small (768px), md- medium (992px), lg- large (1200px)
    • <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 - background
    • class="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)
    • spacing assign responsive-friendly margin 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

JavaScript Basics

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).

  • introduced in Netscape in 1995
  • developed by Brandon Eich
  • named to make use of Java market buzz
  • standardized today as ECMAScript

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:

  • window.alert() - an alert is a pop-up window that displays information (takes a string as a parameter and pauses the JavaScript execution until you press "OK") alert("Hello world!");
  • window.prompt() - very similar to alert, but wants inputconst aNumber = Number(window.prompt("Type a number", ""));
  • document.write() - writes directly to the page document.write("<h1>Time to learn JavaScript</h1>");
  • innerHTML() - combined with the element you want to change, change the contents of the DOM element.innerHTML = “Time to learn JavaScript ”;
  • console.log() - write the data to the browser console (place to see what is going on during the execution of your program, provides debugging information) console.log(“Leave a secret message”);

Document Object Model (DOM)

Programming interface for web documents (represents the page that programs can change the document structure, style, and content).

  • structures documents like a tree, every node has one parent, and possibly many children
  • nodes have properties, methods, and events
  • all of the properties, methods, and events available for manipulating and creating web pages are organized into objects.
  • scripting languages (JavaScript) use the DOM to interact with the document
  • accessing the DOM is done with an API - Application Programming Interface

Data types being passed around the API:

  • Document (the root of the page) - when a member returns an object of type document, this object is the root document object itself
  • Node (a node in the tree) - every object located within a document is a node of some kind (element node, but also a text or attribute node)
  • Element - refers to an element or a node of type element returned by a member of the DOM API
  • NodeList - an array of elements, like the kind that is returned by the method document.querySelectorAll(). Items are accessed: list.item(1), list[1]
  • Attr - attributes are nodes in the DOM just like elements are (another way to manipulate/change the document)
  • NamedNodeMap - like an array, but the items are accessed by name or index, as they are in no particular order in the list

Most commonly-used interfaces in the DOM:

  • document.getElementById("one") - will go into your document and look for that specific element
  • document.getElementsByTagName("p") - will give you all the elements with a particular tag name in a collection
  • document.getElementsByClassName("blue") - will get all elements that match a particular class
  • document.querySelector("#special .myclass") - returns the first Element within the document that matches the specified selector, or group of selectors
  • document.querySelectorAll("#special p") - returns a static NodeList representing a list of the document's elements that match the specified group of selectors
  • document.createElement("p") - creates the HTML element specified by tagName
  • document.createTextNode("paragraph") - put text in element
  • Element.innerHTML - gets or sets the HTML or XML markup contained within the element
  • Element.className - allows you to set the class, or classes for an element
  • Element.classList - read-only property that returns a live DOMTokenList collection of the class attributes of the element
  • Element.setAttribute("name", "helloButton") - sets the value of an attribute on the specified element
  • Element.getAttribute("id") - returns the value of a specified attribute on the element
  • Element.removeAttribute("align") - removes the attribute with the specified name from the element
  • Element.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 target
  • HTMLElement.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 node
  • Node.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 images
  • window.scrollTo({top: 0, left: 0, behavior: "smooth"}) - scrolls to a particular set of coordinates in the document
  • window.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 amount
  • setInterval(func, delay, arg1, arg2, …argN) - repeatedly calls a function or executes a code snippet, with a fixed time delay between each call
  • setTimeout(functionRef, delay, param1, param2, …paramN) - sets a timer which executes a function or specified piece of code once the timer expires
  • location.reload() - reloading the current page

Istance properties of the DOMTokenList (set of space-separated tokens):

  • length - integer representing the number of objects stored in the object const paragraphs = document.querySelectorAll("p").length;
  • value - stringifier that returns the value of the list serialized as a string, or clears and sets the list to the given value const paragraphs = document.querySelectorAll("p").value;

Istance methods of the DOMTokenList:

  • add() - adds the given tokens to the list, omitting any that are already present add(token1, token2, /* …, */ tokenN)
  • contains() - returns a boolean value — true if the underlying list contains the given token, otherwise false contains(token)
  • item() - returns an item in the list, determined by its position in the list, its index tokenList.item(index)
  • remove() - removes the specified tokens from the list remove(token1, token2, /* …, */ tokenN)
  • replace() - replaces an existing token with a new token replace(oldToken, newToken)
  • toggle() - removes an existing token from the list and returns false (if the token doesn't exist it's added and the function returns true) toggle(token)

Events

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).

  • the user selects, clicks, or hovers the cursor over a certain element (click, mouseover / mouseout)
  • the user chooses a key on the keyboard (keydown)
  • the user resizes or closes the browser window (resize)
  • a web page finishes loading (load)
  • a form is submitted (submit)
  • a video is played, paused, or ends (play, pause, ended)
  • an error occurs ("error")

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

Variables, Functions, Data types, OOP

Variables

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

  • variable names consist of letters, digits, underscores, and dollar sign($)
  • are case-sensitive, should be mnemonic (meaningful), must not start with a number, avoid using JavaScript reserved words
  • safe convention - lower camel case (stick together multiple words using lower case for the first word and then capitalize subsequent words)
  • 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 value
  • const - declares block-scoped local variables (cannot be redeclared by any other declaration in the same scope)

Data types

  • Numbers - you don't need to declare variable types in JavaScript, can store numbers in variables (whole numbers - integers or decimal numbers - floats)
  • Strings - a string is a collection of characters
    • to create a string, you put the value in quotes, double or single
    • escaping - done using the backslash character
    • JavaScript string concatenation uses "+", "."operator automatically converts non-string values to strings as needed
    • if a string cannot be converted to a number, you end up with "Not a Number" or "NaN"
    • properties and methods
      • 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 string
      • slice() - 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)
  • Booleans - in programming, a boolean value is one that is either true or false (generally used to test a condition, after which code is run as appropriate)
  • Arrays - is a single object that contains multiple values enclosed in square brackets and separated by commas
    • store multiple value using a variable name, and an index for each element in the array
    • each value is called an element, elements are referenced by index
    • the elements in the array DON'T have to be all the same type
    • have attributes and methods
      • length - represents the number of elements in that array
      • sort() - sorts the elements of an array in place and returns the reference to the same array, now sorted
      • push() - adds the specified elements to the end of an array and returns the new length of the array
      • pop() - 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 string
      • toString() - returns a string representing the specified array and its elements
      • values() - returns a new array iterator object that iterates the value of each item in the array
      • forEach() - executes a provided function once for each array element
      • map() - creates a new array populated with the results of calling a provided function on every element in the calling array
      • reduce() - 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 element
      • splice() - changes the contents of an array by removing or replacing existing elements and/or adding new elements in place
      • indexOf() - returns the first index at which a given element can be found in the array, or -1 if it is not present
    • Array iteration - for (i = 0; i < array.length; i++){...}
  • Objects - represents one of JavaScript's data types (used to store various keyed collections and more complex entities) const person = {name:["Bob","Smith"], age:32, intr(){console.log(`I'm ${this.name[0]}`);};
    • the object person has 3 properties: name, age as data properties and intr() as method
    • person.age; - access the object's properties and methods using dot notation
    • person.["name"][0]; - or using use square brackets
    • person.age = 45; - set (update) the value of object members
    • const myDataName = "height"; const myDataValue = "1.75m"; person[myDataName] = myDataValue; - set the value of member names
    • this 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 keyword

Expressions and operators

  • Primary expressions - basic keywords and general expressions (highest precedence) - this, [], {}, function, class, function*
  • Left-hand-side expressions - left values are the destination of an assignment - new, super
  • Increment and decrement - postfix/prefix increment and postfix/prefix decrement operators - i++ postfix increment, i-- postfix decrement, ++iprefix increment, --iprefix decrement
  • Unary operators - an operation with only one operand - delete, void, typeof, ~ bitwise not, ! logical not
  • Arithmetic operators - take numerical values as their operands and return a single numerical value - ** exponentiation, * multiplication, / division, % remainder, + addition, - subtraction
  • Relational operators - compares its operands and returns a boolean value based on whether the comparison is true - < less then, > greater then, <= less then or equal, >= greater then or equal, istanceof, in
  • Equality operators - the result is always of type boolean based on whether the comparison is true - == equality, != inequality, === strict equality, !== strict inequality
  • Bitwise shift operators - operations to shift all bits of the operand - <<bitwise left shift, >> bitwise right shift, >>> bitwise unsigned right shift
  • Binary bitwise operators - treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values - &AND, | OR, ^ XOR
  • Binary logical operators - implement boolean (logical) values and have short-circuiting behavior - && logical AND, || logical OR, ?? nullish coalescing
  • Conditional (ternary) operator - returns one of two values based on the logical value of the condition (condition ? ifTrue : ifFalse)
  • Assignment operators - assigns a value to its left operand based on the value of its right operand - = assignment, *= multiplication assignment, /= division, %= remainder, += addition, -= subtraction
  • Yield operators - pause and resume a generator function
  • Comma operator - allows multiple expressions to be evaluated in a single statement and returns the result of the last expression - x = (2, 3); console.log(x); //3

Statements and declarations

  • for - creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement for (let i = 0; i < 9; i++){str = str + i;}
  • for...in - iterates over all enumerable string properties of an object including inherited enumerable properties for (const property in object) {console.log(`${property}: ${object[property]}`);}
  • for...of - executes a loop that operates on a sequence of values sourced from an iterable object (Array, String, TypedArray, Map, Set, NodeList) for (const element of array1){console.log(element);}
  • if...else - executes a statement if a specified condition is truthy if (x > 50){...} else if (x > 5){...} else{...}
  • while - creates a loop that executes a specified statement as long as the test condition evaluates to true while (n < 3){n++;}
  • switch - evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered
  • break - terminates the current loop or switch statement and transfers program control to the statement following the terminated statement
  • continue - terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration

Functions

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 ( )
  • Function parameters are listed inside the parentheses ( ) in the function definition
  • Function arguments are the values received by the function when it is invoked
  • The function keyword can be used to define a function inside an expression const x = function(y){return y * y;};
  • An arrow function expression is a compact alternative to a traditional function expression (more compact and can make code easier to read)
    • function makeUpperCase(aString){return aString.toUpperCase();} - function declaration
    • const 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 parameter
    • const makeUpperCase = aString => aString.toUpperCase(); - remove the curly braces and the return keyword if you have just one statement and it is a return statement
    • if you have more than one parameter, you need to put the parentheses back in, so that the code is not ambiguous
    • if you have no parameters, and more than one line in the function, or it’s not returning a variable, you need to include the parentheses and the curly braces
    • arrow functions can not be used as constructor functions because the scope of the keyword this is different in arrow functions than it is in the more traditional function expression syntax
  • Immediately Invoked Function Expression IIFE is a JavaScript function that runs as soon as it is defined (Self-Executing Anonymous Function)
    • (function(){})();
    • (() => {})();
  • A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action
  • Helper functions:
    • function random(min, max){return Math.floor(Math.random() * (max - min + 1)) + min;} - returns a random number in the range between the two numbers
    • function randomRGB(){return `rgb(${random(0, 255)},${random(0, 255)},${random(0, 255)})`;} - generates a random color represented as an rgb() string

Classes

  • class Person {name; constructor(name){this.name = name;} intr(){console.log(`I'm ${this.name}`);}}
  • declares a class called Person, a name property, a constructor that takes a name parameter that is used to initialize the new object's name property, an intr() method that can refer to the object's properties using this

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);});

Prototypes & Inheritance

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 methods

  • Object.assign() - copies all enumerable own properties from one or more source objects to a target object
  • Object.create() - creates a new object, using an existing object as the prototype of the newly created object
  • Object.keys() - returns an array of a given object's own enumerable string-keyed property names
  • Object.values() - returns an array of a given object's own enumerable string-keyed property values
  • Object.hasOwn() - returns true if the specified object has the indicated property as its own property

Regular expressions

are 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)
  • simple patterns are constructed of characters for which you want to find a direct match
  • you can include special characters in the pattern when the search for a match requires something more than a direct match

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 null
  • test() - executes a search with this regular expression for a match between a regular expression and a specified string

jQuery

jQuery 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>

  • Adding jQuery to your project adds some weight to the files and they will take longer to load
  • if you want to get a simple interaction working quickly and easily it may save you a lot of time
  • You can download the library into your project and link to the file locally in your project folder
  • You can "hot link" to the library on a CDN, or Content Delivery Network

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

Asynchronous JavaScript

AJAX - Asynchronous JavaScript and XML

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

XMLHttpRequest

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)
  • Properties, methods and events
    • 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 sent
    • response - returns the response's body content as an ArrayBuffer, a Blob, a Document, a JavaScript Object, or a string
    • status - 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(){});

Fetch API

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 available
  • Headers - 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 JSON
  • Response - represents the response to a request

FormData() - 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 exist
  • delete() - deletes a key and its value(s) from a FormData object
  • entries() - returns an iterator which iterates through all key/value pairs contained in the FormData
  • get() - returns the first value associated with a given key from within a FormData object
  • has() - returns whether a FormData object contains a certain key
  • keys() - returns an iterator which iterates through all keys contained in the FormData
  • set() - sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist
  • values() - returns an iterator which iterates through all values contained in the FormData

Promise

represents the eventual completion (or failure) of an asynchronous operation and its resulting value

  • a Promise is in one of these states:
    • pending: initial state, neither fulfilled nor rejected.
    • fulfilled: meaning that the operation was completed successfully
    • rejected: meaning that the operation failed

Async and Await

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 name
  • await 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)

Data formats

JSON - JavaScript Object Notation

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

XML - Extensible Markup Language

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)

  • XML language is a way to structure data for sharing across websites
  • it looks a lot like HTML, except that you make up your own tags
  • to read and update, create and manipulate an XML document, you will need an XML parser