Beginning Programming / Web Development CheatSheet

Text Editor (Visual Studio Code)

User Interface

Ref: code.visualstudio.com/docs/getstarted/userinterface
Activity Bar
IconShortcutAction
Shift+Cmd+EExplorer (File Tree)
Shift+Cmd+FSearch
Shift+Cmd+GSource Control (Git)
Shift+Cmd+DRun and Debug (Code Debugger)
Shift+Cmd+XExtensions (Install 3rd party extensions)
Manage (Settings, Shortcuts, Snippets, Themes)

Run Terminal

Terminal menu > New Terminal

Add Extensions

Click the Extensions icon > Type in the extension name > click Install
Examples
Live Server:
  • Find and install the Live Server extension. This allows you to run a web server that automatically reloads every time you save a file in your web project: 
Click the Extensions icon on the Activity Bar > type "Live Server" in the search box > click Install
  • To use Live Server: Open an HTML document in VS Code > Right click in the Editor > select "Open with Live Server". The HTML page will automatically open in your default web browser.

JavaScript ES6 Code Snippets:
  • Find and install the JavaScript ES6 Code Snippets extension.
Click the Extensions icon on the Activity Bar > type "JavaScript ES6 Code Snippets" in the search box > Click install 
  • To use ES6 Snippets: Type in a shortcut followed by tab and the snippet will be added.

Launch Live Server

Rt click on HTML page > Open with Live Server
The page will open in the browser at http://127.0.0.1:5500
Stop Live Server: Rt click page in VS Code > Stop Live Server

Command Pallet

Cmd+Shift+P Open Command Pallet.
Access all available commands based on your current context.
code.visualstudio.com/docs/getstarted/tips-and-tricks#_command-palette

Change Color Theme

Code menu > Preferences > Color Theme > Select theme

Change Settings

  1. File/Code menu > Preferences > Settings or click Manage icon > Settings
  2. Type in settings property name in the search box.
Examples
  • Tab size: Search for Tab Size > value: 2 or 4
  • Word wrap: Search for Word wrap > value: on or off
  • Minimap: Search for minimap > check or uncheck Minimap: Enabled.
  • Enable Preview: Search for enable preview > check or uncheck Editor: Enable Preview.
  • Vertical Rulers: Search for rulers > click Edit in settings.json > set "editor.rulers" to "editor.rulers": [80, 100], or some other number(s) > Save the file.
  • Optionally, disable popup hints/suggestions and breadcrumbs:
    • Quick suggestions: Search for quick suggestions > "other" value off.
    • Hover (shows hints when hovering over your code): Search for hover > uncheck Hover: Enabled.
    • Parameter hints: Search for parameter hints > uncheck Parameter Hints: Enabled.
    • Suggest on trigger characters: Search for Suggest on trigger characters > uncheck Editor: Suggest on trigger characters.
    • Breadcrumbs: Search for breadcrumbs > uncheck Breadcrumbs: Enabled.

Keyboard Shortcuts

Ref: code.visualstudio.com/docs/getstarted/keybindings
ActionMacWindows
Full listMacOS.pdfWindows.pdf
CutCmd+XCtrl+X
CopyCmd+CCtrl+C
PasteCmd+VCtrl+V
UndoCmd+ZCtrl+Z
RedoCmd+Shift+ZCtrl+Y
IndentTabTab
UnindentShift+TabShift+Tab
Toggle commentCmd+/Ctrl+/
Toggle block commentShift+Alt+AShift+Alt+A
Scroll to bottomCmd+DownArrowCtrl+DownArrow
Scroll to topCmd+UpArrowCtrl+UpArrow
Move line downAlt+DownArrowAlt+DownArrow
Move line upAlt+UpArrowAlt+UpArrow
Copy line downShift+Alt+DownArrowShift+Alt+DownArrow
Copy line upShift+Alt+UpArrowShift+Alt+UpArrow
FindCmd+FCtrl+F
Find and ReplaceCmd+Alt+FCtrl+H
Search all files in projectShift+Cmd+FShift+Ctrl+F
Quick Open, Go to File…Cmd+PCtrl+P
Toggle sidebar visibilityCmd+BCtrl+B
Collapses selected file listLeftArrowLeftArrow
Collapse all file listsCmd+LeftArrowCtrl+LeftArrow

Change Shortcut Keys

Code > Preferences > Keyboard Shortcuts > Search Box: Type in command
View all customized keyboard shortcuts: 
Code > Preferences > Keyboard Shortcuts > Click Open Keyboard Shortcuts icon 
Example Changes
Redo: Cmd+Y
Replace: Cmd+H
BlockComment: Shift+Alt+/

Snippets

List all snippets: Shift+Cmd+P > Insert Snippet > Select a snippet

Emmet abbreviations and snippets (HTML and CSS)

Instructions: code.visualstudio.com/docs/editor/emmet
Full list docs.emmet.io/cheat-sheet
HTML Snippets
!→ Generate a skeleton HTML document.
</ Auto closes open tag.
tag Generate tags <tag></tag>   
tag#id Generate tags with id <tag id="id"></tag>
tag.className Generate tags with class <tag class="className"></tag>
tag.class1.class2 Generate tags with two classes <tag class="class1 class2"></tag>
tag#id.class Generate tags with id and class <tag id="id" class="class"></tag>
Examples
p→ Generate p tags <p></p>
h1#main-heading→ Generate h1 tags with id <h1 id="main-heading"></h1>
h2.text-center→ Generate h2 tags with class <h2 class="text-center"></p>
img.rounded.float-start→ Generate tag with two classes <img class="rounded float-start">
div#ex-1.border  Generate div tags with id and class <div id="ex-1" class="border"></div>

Terminal / Command-line Interface

Notation symbols and conventions used in this CheatSheet
lowercase-italics, <generic item type>, [optional item], keyboard shortcuts
Throughout this CheatSheet we will use the below symbols and conventions to document commands:

lowercase-italics Words in italics indicate the item is a user provided variable. You must substitute the appropriate names or values.
Example: 
help command_name The user enters the specific command name they want help on. 
help mkdir mkdir is the command name to get help on.


< > Angle brackets contain a generic item type. You must substitute it with the appropriate values. The angle brackets themselves are not typed.
Example:
find <path> -name <filename> The user enters the path, and the filename.
find /users/steve/documents -name myfile.txt Replace path with the path to the documents directory. Replace filename, with the file to find.


[ ] Square brackets contain optional items. The square brackets themselves are not typed.
Example:
command [-options] [arguments] The options and arguments are optional
ls Here I execute the ls command with no options or arguments
ls /users/steve/documents Here I execute the ls command with the path argument.
ls -a /users/steve/documents Here I execute the ls command with the -a option and the path argument.


 |  Items separated by a single vertical bar are alternative items. You can select only one of the group of items separated by single vertical bars. The vertical bar itself is not typed.
Example: 
--color | colour For the color option, you can enter color or colour.

Note: don't confuse this with the Unix pipe symbol.


Keyboard Shortcuts:
  • Mac keyboard shortcuts generally use the Command key.
  • Windows keyboard shortcuts generally use the Control key.
  • By convention, keyboard commands are written like Command+C. This means to press the Command key and the lower case "c" key simultaneously.
  • Mac and Windows usually, but not always, use the same key combinations for the shortcuts, so they could be expressed as commandOrControl+C.

Command-Line Interface

Command-line interface (CLI): is an interface for entering text-based commands.
Mac Terminal application: Terminal emulator that accesses the Unix shell application.
Windows PowerShell: Default command-line shell that interfaces with File Explorer.
Terms: CLI, terminal, console, shell, Z Shell, Bash, Unix
  • CLI/Terminal/Console: The terms command-line interface (CLI), terminal, and console are often used interchangeably. They refer to the software application that provides an interface for entering text commands. 
    • Terminal: is also the name of Mac's terminal application. It emulates a computer terminal providing a command-line interface as well as some Graphical User Interface (GUI) features like tabs, copy/paste, etc. It automatically opens a Unix Shell application which interfaces with the computer's operating system.
  • Shell: A Shell program is a command-line interpreter program that executes commands on the operating system's services.
    • PowerShell: is the default command-line shell for Windows. It interfaces with File Explorer.
    • Unix shell program: Command-line interpreter that interfaces with the Unix operating system. There are several Unix shell programs. The two most commonly used are:
      • Z Shell (zsh): This is the default Unix Shell program used in MacOS.
      • Bash: is the default command shell for most Linux distributions

  • Unix: is a family of operating systems first published in 1971. It is used by MacOS/iOS, and the majority of servers.
  • Unix-like operating systems: Unofficial umbrella term for operating systems that behave like a Unix system, whether or not they are certified as following the Single UNIX Specification. Includes Linux.

Command Syntax

command [-options] [arguments] Optional parameters: options, arguments.
  • Command: The command name comes first.
  • Options (aka flags): Modify how the command does its job.
    • -<character> Unix options use single dash and one character.
    • -<char1><char2> or -<char1> -<char2> Apply multiple options.
    • --option-keyword Some Unix versions allow long options.
  • Arguments: Pass information to the program you want to run. Typically zero, one, or multiple arguments specify the data upon which the program will perform an action.
Examples
The ls list command:
  • ls  The list command lists the items in the current directory.
  • ls -l ls has a number of options you can add to it. Applying the -l long option will return extra information about each item including the permissions, owner, size, date last modified, and name.
  • ls -lh Applying the -h human readable option will show the item size as B bytes, K kilobytes, M megabytes, or G gigabytes which make them easier to read. You can add both options individually ls -l -h but it is more common to combine them after a single dash.
  • ls -lha Applying the -a option will show all items including hidden files that start with a dot.
  • ls -lha ~/Documents ls works on the current directory by default. If you want to show the items in a different directory you need to add the path as an argument. To show the items in the Documents directory add the absolute or relative path as an argument.
  • ls -lha ~/Documents ~/Desktop A command can have multiple arguments. To show the items in both the Documents and Desktop directory list them both as arguments separated by a space.

Long Option example: Node version
  • Assuming Node.js is installed on your machine, the node command you launches the node program.
  • The version option returns the version of the node program instead of launching it. Version has both a short and long option:
    • node -v 
    • node --version
Case: Unix/Linux is case sensitive. Generally use lower case for everything.
Quotes: Either single or double quotes around strings: echo 'Hello'; echo "Hello"

When typing a command:
enter/return Enter the command. Cursor can be anywhere on the line you want to enter.
left | right arrow Move the cursor one character to the left or right.
Ctrl+A Move the cursor to the beginning of the line.
Ctrl+E Move the cursor to the end of the line.
up | down arrow Up gets the previously entered command. Down goes back down.
partial command + tab Unix tries to guess the rest of the command or filename.

Useful Commands

Mac Terminal | Win Powershell keyboard shortcuts:
Cmd+N | Ctrl+Shift+N Open new terminal window.
Cmd+T | Ctrl+Shift+T Open new terminal tab.
Cmd+F | Ctrl+Shift+F Find.
Cmd+C | Ctrl+C Copy selected text.
Cmd+V | Ctrl+V Paste.
clear | Ctrl+L Clear the screen. Scrolls to last line without removing previous lines.
Cmd+K | clear  Clear the screen. Removes all previous lines.
Run Other Shell Programs in the Terminal:
program_name Start the program
Ctrl+C Close an operation in the program (without exiting the program).
Ctrl+D Exit the program.
program_name --version Returns the version of the program if it is installed.
which program_name Returns the executable file path which is called by the command.

File System

  • Mac and the majority of servers use Unix or Unix-like operating systems. 
  • The below commands work both in Unix shells and PowerShell. 
  • File systems are like an upside down tree with the root at the top and branches going down.

Directories

pwd Present working directory: Returns the absolute path of the directory you are in.
/ Root directory
~ Home directory (/Users/username)
./ the current directory
Make Directories:
mkdir directory_name Create directory 

Change Directories

Absolute path: starts from the root directory /.
Relative path: starts from your present working directory. 
cd path Change directory to the path argument.
./ is the current directory.
cd .. Up one directory.
cd ../../path/to/directory_name Up two directories then down three.
cd /path  Start from the root directory.
cd ~ Go to user's home directory (/Users/username).
cd ~/path Start from user's home directory.
Forward vs backslashes, folder names with spaces, c: optional, case sensitivity
  • While Windows allows you to use either forward slash or backslash, Linux only allows forward slash. As such you may want to use only forward slash as a habit.
  • If a folder has a space in it, you must put it in quotes: /"program files"/directoryname
  • Including c: when referencing the root directory in Windows is optional.
  • Case sensitivity: Unix is case sensitive, but case sensitivity for directory and file names depends on the underlying operating system's file system. MacOS's file system, for instance, is not case sensitive.

List Files and Directories

ls List all files and directories in the current directory.
ls -p Distinguish directories by appending "/" after the name.
ls -A All files & directories including hidden files (with dot in front of them).
ls path List all files & directories in the given path.
Show/hide system files
In Unix, system files start with a dot and are hidden. 
In the Mac Finder program you can press Cmd+Shift+. to show or hide the system files.

Web Pages: HTML

Create an empty HTML file: index.html
Generate a basic HTML document with a VS Code snippet: !+tab
The generated HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
</body>
</html>

Open the web page in the browser

  • Open the HTML file with the browser:
    • Open the browser > click the file menu > open the index.html file.
    • Or double-click the HTML file in Mac Finder or Windows File Explorer.
  • Launch the web page with the VS Code Live Server extension:
    • Right-click on the HTML page in the editor > select "Open with Live Server".
    • When done, right-click the HTML page in the editor > select "Stop Live Server".

HTML Elements and Tags

  • An HTML document is broken down into elements that represent different types of data indicated by the element's tag name.
  • Full list of elements: developer.mozilla.org/en-US/docs/Web/HTML/Element
  • Elements that contain text or other HTML elements have opening and closing tags.
Single tags vs opening and closing tags
Elements that contain text and/or other elements as content use opening and closing tags with the content between them: <p>This is text content.</p>
Elements that do not contain text other elements as content use a single tag. Common examples include:
  • <img> Image tags.
  • <hr> Horizontal line tags.
  • <input> Form field input elements.
  • <link> Link tags to stylesheets and the favicon image. 
Main Root:
  • <html> Wrap the entire HTML document in html tags. This is the root element.
Document metadata:
  • <head> At the top of the HTML document put metadata about the page in head tags.
  • <title> The document title is displayed in the browser tab.
  • <link rel="stylesheet" href="path/stylesheet"> Link to the stylesheet.
  • <link rel="icon" type="image/x-icon" href="path/image"> Link to the favicon image.
  • <script src="path/JavaScript.js" defer></script> Get JavaScript from the src (source) file.
Example
<head>
  <link rel="icon" type="image/x-icon" href="images/favicon.png">
  <link href="stylesheets/styles.css" rel="stylesheet"> <script src="script.js" defer></script>
  <title>Page or Site title</title>
</head>
Content sectioning:
  • <body> Contains the content of the HTML document. Can only be one body element.
  • <nav> Put navigation links or table of contents in the nav element.
  • <main> Optionally put the main content in main tags.
  • <h1> to <h6> Heading text. h1 is the top level, h6 is the lowest heading level.
  • <footer> Put footer content like copyright and some links in footer tags.
Example
<body>
  <nav>navbar links go here</nav> <main>
  <h1>Page heading text goes here</h1>
  ... </main>
  <footer>footer content goes here</footer>
</body>
Text content:
  • <div> Division element. Generic container for a block element. 
  • <p> Paragraph element.
  • <hr> Horizontal rule. Creates a horizontal line across the page to separate content.
Example
<h2>First topic</h2>
<p>Paragraph text</p>
<p>Another paragraph text</p>
<hr>

<h2>Second topic</h2>
<p>Paragraph text</p>
<p>Another paragraph text</p>
<hr>
Ordered and Unordered Lists:
  • <ul> Unordered list: Create a bullet point list by putting list items inside ul tags.
  • <ol> Ordered list: Create a numbered list by putting list items inside ol tags.
  • <li> List item: Put li tags inside the ul or ol element. Put list item content in li tags.
Example
  • Unordered list:
<ul>
  <li>List item.</li>
  <li>Another list item.</li>
</ul>
  • Ordered list:
<ol>
  <li>First item.</li>
  <li>Second item.</li>
</ol>
Inline text semantics:
  • <span> Generic container for inline content.
  • <b> Bold text. Used to draw the reader's attention to the element's contents.
  • <i> Italic text. Used to set the text off from the normal text for some reason. 
  • <small> Makes the text smaller than the rest of the text in the parent element. 
  • <a href="url">link text</a> Creates a hyperlink. Put the URL in the href attribute.
  • <br> Produces a line break in the parent element's text.
Examples
<p>
  <b>Bold text</b> 
  <i>Italic text</i><br>
  <small>Smaller text</small>
  <span>Generic inline element</span><br>
  <a href="https://www.example.com">example website</a>
</p>
Images:
  • <img src="image-file" alt="alt text" width="x" height="y"> Embeds image in the document. 
    • The src (source) attribute value is the path to the image file. 
    • The alt attribute is short text description of the image. 
    • Optionally add width and/or height attributes set to the number of pixels to set the width or height to. The image's intrinsic width and height is the default.
Example
  • Display a diagram image. Use the intrinsic width and height.
    • <img src="images/diagram.png" alt="Diagram"> 
  • Display a diagram image. Set the width property to 500 pixels. The height will be set automatically.
    • <img src="images/diagram.png" alt="Diagram" width="500"> 
  • Display a diagram image. Set the height property to 300 pixels. The width will be set automatically.
    • <img src="images/diagram.png" alt="Diagram" height="300">
Forms:
  • <form> Put form content in a form element.
  • <label for="field-id"> Form field label. Set for attribute to the form field id value.
  • <input id="field-id" name="field-name" type="data-type"> Form field. Accepts user input.
    • Type attribute sets the field's data type (e.g., text, number, date, email, password)
    • Name attribute is used for the field data when submitting the form to the server.
  • <textarea id="field-id" name="field-name" rows="n"> Form field for multiple lines of text.
    • Rows attribute sets the number of rows the field displays. The default is 2. 
  • <button type="submit"> Interactive button element activated when clicked. 
    • When type is set to "submit" it submits the form data when the button is clicked. 
Example
<form>
  <div>
    <label for="field1">Short text field 1</label>
    <input id="field1" name="field1" type="text">
  </div>
 
  <div>
    <label for="field2">Number field 2</label>
    <input id="field2" name="field2" type="number">
  </div>
 
  <div>
    <label for="field3">Long text field 3</label>
    <textarea id="field3" name="field3" rows="4"></textarea>
  </div>
  <button type="submit">Save</button>
</form>

Element Attributes

  • Attributes give information about an element. Put them in the opening tag.
  • Global attributes can apply to all elements:
    • id defines an identifier. Id should be unique in the whole document.
    • style applies style directly to an element. Format: style="cssProperty: value;"
    • class apply classes from the CSS stylesheet to the element.

Comments:

  • Comment syntax: <!-- comment goes here -->

Web Pages: CSS / Stylesheets

CSS / Stylesheets

  • Style web pages by creating a stylesheet file ending with a .css extension
  • In the HTML document's head element create a link to the stylesheet.
    • <link href="stylesheets/styles.css" rel="stylesheet">
Example
The HTML file includes a link to a stylesheet located in stylesheets/styles.css
<head>
  ...
  <link href="stylesheets/styles.css" rel="stylesheet">
</head>

Style Rule Structure:

  • Style rule: Determines the styles applied to elements.
  • Selector: Patterns used to match, or select, the elements you want to style.
    • Type selector: tagName { declarations } match all elements by the tag name. 
    • Class selector: .className { declarations } match all elements by the class name.
    • Id selector: #id { declarations } match all elements by the element id. 
  • Declaration Block: Put declarations for a given selector in curly braces. 
  • Declaration: CSS property name and value separated by a colon. 

CSS Syntax:

  • Use lower case letters for tags, id values, class names, properties. 
  • Separate multiple words with hyphens.
  • Use semicolons after every declaration.
  • Use single quotes for values that include spaces: font-family: 'Times New Roman';

  • For style rules use separate lines for each property:
body {
  font-size: 14px;
  background-color: #fbfbf8; 
}
  • Optionally, put short style rules on one line:
body { font-size: 14px; background-color: #fbfbf8; }

  • Comments: /* Comments here */

CSS Properties

Color

  • color Sets the text color.
  • background-color Sets the element's background color.
Color values:
Examples and more info on hex number
Hexadecimal string notation: This format starts with a # sign followed by 6 hexadecimal digits using red green blue color combinations: #rrggbb. Hexadecimal numbers are base 16 represented by numbers 0-9 and letters A-F. There are two digits for each color which allows 256 possible values each for red, green and blue. The letters are case insensitive.

Examples:
Set color for the whole body element. Using named color values:
  • body { color: black; background-color: ghostwhite; } 
Create class that sets text color to white and background color to black using hex numbers.
  • .dark-theme { color: #ffffff; background-color: #000000; }

Font family

  • font-family Sets the font. Default font is Times or 'Times New Roman'. 
  • Serif fonts: Have tails on the ends of letters. Popular examples: Times, Georgia
  • Sans-serif fonts: Do not have serifs. Popular ex: Arial, Helvetica, Tahoma, Roboto
Example
Set the font family for the whole document body element.
body { font-family: Arial; }
Length units and percentages
  • px: measures length in number of pixels. One pixel represents 1/96th of an inch.
  • %: measures length as percent of available space. 100% takes up all available space.
Examples
  • Create a shrink class that sets the font size to 12 pixels:
.shrink { font-size: 12px; }
  • Image will not take up more than 100% of the available width. It will shrink to fit the screen if the screen is narrower than the image width.
.img { max-width: 100%; }

Font size

  • font-size Sets the font size. Default font size in web browsers is 16px.
Example
  • Create a shrink class that sets the font size to 12 pixels:
.shrink { font-size: 12px; }

Margin, Border, Padding


  • margin Margin is space around an element separating it from the adjacent elements.
  • padding Padding is the space between the content and the edge of the element.
  • border Shorthand property: border: width style color; (e.g., border: 1px solid black;)
      • Style values: solid, dashed, dotted, double, groove, ridge, inset, outset.
  • border-radius Create rounded corners on borders.
  • One value: Set all 4 sides with the same value (replace n with the number of pixels): 
    • margin: npx; | padding: npx; | border: npx style color; 
  • Two values: First value sets the top and bottom. Second value sets the left and right:
    • margin: npx npx; | padding: npx npx; 
  • Individual sides: To set one side only, add the side to the property name:
    • margin-top: npx; | margin-bottom: npx; | margin-left: npx; | margin-right: npx;
    • padding-top: npx; | padding-bottom: npx; | padding-left: npx; | padding-right: npx;
    • border-top: npx style color; | border-bottom: ... | border-left: ... | border-right: ...
Examples
  • Given a div element with class box: 
<div class="box">box me in</div>

  • In the stylesheet set the box class to have margin of 16px on top and 16px on bottom. 
  • Add a 2 pixels wide solid red border around it with rounded corners.
  • Add padding of 2 pixels on the top and bottom, and 4 pixels on the left and right.
.box {
  margin-top: 16px;
  margin-bottom: 16px;
  border: 2px solid red;
  border-radius: 4px;
  padding: 2px 4px;
}

Width and height

  • width Set the width of an element in px (pixels) or % (percent) of available space.
  • min-width Set the minimum width of an element. 
  • max-width Set the maximum width of an element. 
  • height You can also set the height of some elements like images.
Examples
Assign a class named "gallery" to three images. In the class set width to 300px and height to 200px.
  • <img src="..." alt="..." class="gallery">
    <img src="..." alt="..." class="gallery">
    <img src="..." alt="..." class="gallery">
  • .gallery { width: 300px; height: 200px; }

Assign a class called "single-img" and a width attribute of 600 pixels to an image. In the class set max-width to 100%. That will cause the image to shrink if it exceeds the available width.
  • <img src="..." alt="..." class="single-img" width="600">
  • .single-img { max-width: 100%; }

Web Pages: Bootstrap Front-end Framework

Download Bootstrap and put it in your app or use the CDN links from getbootstrap.com.

Bootstrap Colors

Ref: getbootstrap.com/docs > click Utilities: colors
Class names: Set color property text-color, Set background-color property bg-color, Set button color property btn-color
Color names:
  • primary blue #0d6efd;
  • secondary grey #6c757d;
  • success green #198754;
  • danger red #dc3545;
  • warning yellow #ffc107;
  • info light blue #0dcaf0;
  • light light grey #f8f9fa;
  • dark blackish #212529;
  • text-white white #ffffff; 
  • text-muted grey #6c757d;
  • primary-emphasis dark blue #052c65;
  • secondary-emphasis dark grey #2b2f32;
  • success-emphasis dark green #0a3622;
  • danger-emphasis dark red #58151c;
  • warning-emphasis dark yellow #ffc107;
  • info-emphasis dark aqua #0dcaf0;
Examples
  • <span class="text-danger">There was an error</span> Color text red.
  • <span class="text-danger-emphasis">There was an error</span> Color text dark red.
  • <footer class="bg-light"> Set the footer background color to light grey.
  • <button class="btn btn-secondary"> Set the button color to grey.

Bootstrap margin and padding

Ref: getbootstrap.com/docs > click Utilities: spacing
Class name format: Property[Side]-Size 
Property: m margin | p padding
Side: t top | b bottom | s start/left | e end/right | x left & right | y top & bottom
If side is absent the class applies to all four sides.
Size: 1 4px | 2 8px | 3 16px | 4 24px | 5 48px
Examples
 Add 16px margin to all sides, one side, and two sides:
  • <div class="m-3"> Add 16 pixels margin to all four sides.
  • <div class="mt-3"> Add 16 pixels margin to the top.
  • <div class="mb-3"> Add 16 pixels margin to the bottom.
  • <div class="ms-3"> Add 16 pixels margin to the left (start).
  • <div class="me-3"> Add 16 pixels margin to the right (end).
  • <div class="my-3"> Add 16 pixels margin to the top and bottom.
  • <div class="mx-3"> Add 16 pixels margin to the left and right.

Add padding to all sides using different sizes:
  • <div class="p-1"> Add 4 pixels padding to all four sides.
  • <div class="p-2"> Add 8 pixels padding to all four sides.
  • <div class="p-3"> Add 16 pixels padding to all four sides.
  • <div class="p-4"> Add 24 pixels padding to all four sides.
  • <div class="p-5"> Add 48 pixels padding to all four sides.

Bootstrap border

Ref: getbootstrap.com/docs > click Utilities: borders
  • border Puts a border on all four sides.
  • border-top Puts a border on the top.
  • border-bottom Puts a border on the bottom.
  • border-start Puts a border on the left side.
  • border-end Puts a border on the right side.
Example
Add a border to the top of the footer element.
<footer class="border-top"> 

Bootstrap container

Ref: getbootstrap.com/docs > click Layout: Containers
  • container a responsive fixed-width container. Its max-width changes at 5 breakpoints to set widths: 540px, 720px, 960px, 1140px, 1320px.
  • container-fluid a full width container spanning the entire width of the viewport.
Examples
Place a div after the navbar and before the footer.
  • <div class="container">...</div>

Bootstrap List Groups

Ref: getbootstrap.com/docs > click Components: list-group
  • list-group Puts a border around the list.
  • list-group-numbered Displays numbers in the list.
  • list-group-item Puts border around the list item and removes the bullet point. 
Examples
Unordered List Example:
<ul class="list-group">
  <li class="list-group-item">An item</li>
  <li class="list-group-item">A second item</li>
</ul>
Ordered List Example:
<ol class="list-group list-group-numbered">
  <li class="list-group-item">Item 1</li>
  <li class="list-group-item">Item 2</li>
</ol>

Bootstrap Images

Ref: getbootstrap.com/docs > click Content: Images
Add the below classes to the img element.
  • img-fluid Make image responsive. Image shrinks when it is wider than the screen.
  • rounded Round the corners.
  • img-thumbnail Add 1px border with rounded corners.
Example
<img src="file-path" alt="alt-text" class="img-fluid img-thumbnail"> 

Beginning JavaScript

Run JavaScript Code

Run JS Code in the Browser with Chrome Dev Tools
Mac: Cmd+Optn+J​ | Win: Ctrl+Shift+J​ | Any OS: Rt-click page > Inspect > Console tab
Run JS code in the Terminal with Node.js
Open the Terminal > enter node​ > enter your JavaScript statements.
Close node: Ctrl+D​ | or enter .exit
Run JS file from the Terminal with Node.js
Open the Terminal in the file's directory > enter node filename​ (.js extension assumed)

Definitions and Syntax

Statement: A line of code that instructs the computer to execute some action.
Code Block: Statements enclosed in {} that execute together (e.g., functions, if block).
Indentation:
 Indent 2 spaces.
Comments: // single line /* multiple lines */ Short explanation of the next line of code.
Semicolons: Put semicolons at the end of each statement, not at the end of code blocks.
Double vs single quotes: Put text strings in single quotes. Double quotes also work.
What is JavaScript?
JavaScript is a programming language run in web browsers and on servers.

JavaScript (often shortened to JS) was first released in 1995 as a simple programming language to run in the Netscape Navigator web browser to manipulate HTML elements without having to reload the page. Shortly afterwards official standards were released to enable JavaScript to be run in any web browser. 

Besides the unique feature of being run in the web browser and interacting with web page, JavaScript also has all the features of a standard programming language. It has variables, functions, if statements, data types, objects, arrays, etc. We will cover the basics of all these in this tutorial.

In 2009 Ryan Dahl created the Node.js runtime environment that lets you run JavaScript programs outside the browser and interact with the host computer's operating system. Since then JavaScript has become a prominent language for running web sites on the server side. There are other languages used to run website on the server side such as Python, PhP, Ruby, and Java. But only JavaScript can be run both client-side (in the browser) and server side. 

Data Types

Programming languages handle data differently depending on what type of data it is. 
JavaScript has 8 data types including 7 primitive data types and an object data type.
The most commonly used data types are:
  • String: text surrounded by quotes. Example: "Hello"
  • Number: numeric values. Example: 7
  • Boolean: true or false
  • Undefined: variables that have not been initialized with a value are undefined.
    • Example: typeof x; // Returns undefined since x has not been initialized.
  • Null: Null is the intentional assignment of no value to a variable. let x = null;
  • Object: Unordered collection of properties written as name:value pairs.
    • Example: { name: 'Joey', age: 22 };
    • Arrays and functions are a type of object.

  • typeof operator will return the datatype of a value: typeof value;
typeof examples
typeof "Hello"; // returns 'string'
typeof 7; // returns 'number'
typeof true; // returns 'boolean'
typeof false; // returns 'boolean'
typeof x; // returns 'undefined', x is a variable name that has not been declared.
typeof { name: 'Joey', age: 22 }; // returns 'object'
typeof [1, 2, 3, 4]; // returns 'object'. Arrays are a type of object.

Variables

  • Variables are containers that store values in memory.
  • Declare a variable: with the keyword let or const followed by an identifierlet x
  • Initialize the variable: by assigning a value to the variable: x = 7;
  • Declare and initialize the variable in one step: let x = 7; 
  • To get the variable's value enter the variable name: x; // returns 7

Difference between const and let:
  • const variables can't change their value, but let variables can. 
  • Use const unless you intend to change the variable's value.
  • Use the let keyword when you declare the variable. After that just use the identifier.
Let examples
let result = 0;
result = 8 * 2; result; // Returns 16 result = 4 + 9; result; // Returns 13
Scope
Scope relates to where variable values can be accessed.
  • Local scope: Variables declared outside any block (e.g., function, if block).
  • Block scope: Variables declared inside a block can only be accessed in that block.
Examples
Example:
In the below example, x is script scoped. It is available anywhere in your script after this point. Y is block scoped. It is only available within this if block.
const x = 1;
if (x > 0) {
  const y = 2; y; // returns 2
}
x; // returns 1
y; // throws ReferenceError: y is not defined

  • To set the value of a variable in an if statement, declare it outside the if statement.
Example:
let result
const score = 80;
if (score > 60) {
  result = 'Pass';
else {
  result = 'Fail';
}
result; // returns 'Pass'
Primitives are stored by value
Variables assigned to primitives (numbers, strings, booleans) are stored by their value:
  • const x = 1; x stores the value 1.
Examples
In the below examples variables x and y are assigned to values the resolve to the value 1. When you compare the variables you are comparing their values. They both hold the number 1 so x and y are equal.
const x = 1;
const y = 3 - 2;
const res = (x === y); // returns true. They both store the value 1. The values are equal.

Below is another example where the values are assigned to the string "hello".
const str1 = 'hello';
const str2 = 'hello';
const res = (str1 === str2); // returns true. They both store the value "hello".


Objects are stored by reference
  • Objects are stored in heap memory. Variables assigned to object values don't store the object value itself, they store a reference to the memory address.
Examples
The below variables are assigned to objects which get stored in heap memory. The variable holds the reference to the object in memory, not the object itself. As such obj1 is not equal to obj2 even though the object properties are identical. 
const obj1 = { name: 'Joey', age: 22 };
const obj2 = { name: 'Joey', age: 22 };
let res = (obj1 === obj2); // returns false

The below example assigns variable objCopy to the value of obj1. Since the value is their location reference value, they are equal. They both contain the same reference value.
const objCopy = obj1;
let res = (objCopy === obj1); // returns true

Expressions

Expression: An expression is any valid unit of code that resolves to a value. 
Primary expressions: Expressions that cannot be evaluated further (e.g., literal value 7)
Examples
  • 4 + 3 is an expression that resolves to 7.
  • 7 is a number literal. It is a primary expression because it is already at it's lowest level.
  • true is a boolean literal and is a primary expression.
  • 5 > 3 is an expression that resolves to true. 

Operators

Operator: A special symbol or keyword used to perform operations on data. Operators are used in expressions. In the expression 4 + 3, the + sign is the operator. 
Operand: The data used in the expression. In expression 4 + 3, 4 and 3 are the operands.
Assignment operator
The assignment operator "=" is used to assign a value to a variable: const x = 5;
Compound assignment operator +=
Compound assignment operator is a shorthand operator to add on to an existing variable.
result += 1; is shorthand for result = result + 1;
Example
Declare variable x initialized to 0. Follow that with three statements that each add 1 to x.
let x = 0;
x = x + 1; // returns 1
x = x + 1; // returns 2
x = x + 1; // returns 3

Declare variable y initialized to 0. Follow that with three statements that each add 1 to y using the compound assignment operator.
let y = 0;
y += 1; // returns 1
y += 1; // returns 2
y += 1; // returns 3

Comparison operators === !== == != > < >= <= 
  • Comparison operators compare two operands and return true or false.
  • greater than >,  greater than or equal to >=, less than <, less than or equal to <=.
  • Strict equality === Checks for equality of the value and data type. 
  • Strict inequality !== Checks for inequality of the value and data type. 
  • Loose equality == Checks for equality of values and does some type conversions.
    • 7 == '7'; When comparing a number to a digit string, convert it to a number.
  • Loose inequality != Checks for inequality of values. Does above type conversions.
Examples
  • Greater than/less than comparison examples:
1 < 2; // returns true
1 <= 2; // returns true
1 > 2; // returns false
1 >= 2; // returns false

  • Strict equality and inequality examples:
7 === (5 + 2); // returns true
7 === '7'; // returns false, they are not the same data type
7 !== '7'; // returns true

  • Loose equality and inequality examples:
7 == '7'; // returns true, '7' is converted to 7 before doing the compare.
7 != '7'; // returns false

Booleans

Booleans
  • Boolean is a primitive data type with two possible values: true or false.
  • Comparison expressions resolve to boolean values: 2 > 1; // returns true
Examples
let name = 'Joey';
let age = 22;
name === 'Joey'; // returns true
age < 21; // returns false.

If Statements

  • An if statement is a block of code that executes if its condition resolves to true. 
  • If the condition resolves to false it is skipped.
if (condition) { 
statements;
}
Example
const score = 77;
let pass = false;
if (score >= 60) {
  pass = true;
}
pass; // returns true
If... else:
It can have an else clause that executes if the condition is false.
if (condition) { 
statements;
} else {
statements;
}
Example
const score = 77;
let pass;
if (score >= 60) {
  pass = true;
} else { pass = false; }
pass; // returns true

Functions

  • Functions are self contained blocks of code that accomplish a specific task. 
  • Functions are not executed until they are called. 
Function declarations
function name(parameters) { 
  statements;
  return statement;


name(arguments);
  • Function declarations start with the keyword function followed by the function name.
  • Parameters act as local variables that hold values passed in when the func is called. 
  • Function Body: Statements inside the curly braces that execute as a block of code. 
  • Return statement: Functions always return a result. 
    • Start the last statement with keyword return then the value the function returns.
    • If there is no return statement, the function returns undefined.
  • Call the function with the function name and parentheses to pass in arguments.
    • Arguments: In the parentheses pass in the values for the function parameters.
Example
The below function adds two numbers together:
function add(x, y) {
  const res = x + y;
  return res;
}
let res = add(5, 3); // returns 8

  • The add function has two parameters, x and y. 
  • The function body adds the two parameter values together then returns the result.
  • We call the function passing in two arguments: 5 and 3. 
  • We assign the function's return value of 8 to the variable res
Hoisting: Function declarations are hoisted to the top of their scope. That means you can call a function before it is declared. 
Example
If you call the add function before it is declared it will still give you the result.
let res = add(5, 3); // returns 8
function add(x, y) {
  const res = x + y;
  return res;
}
Arrow functions
const funcName = (params) => {
  statements;
  return statement;
}
  • The function keyword is removed and replaced with a fat arrow.
  • Assign a const variable to the arrow function. Call the function by the variable name.
  • Const variables are not hoisted. They must be declared before being called.
  • Const variables are block scoped.
Example
const add4 = (x) => {
  const result = x + 4;
  return result;
}
add4(10); // returns 14
Single statement arrow functions
Arrow functions allow a shortened syntax for single statement functions.
Put them on a single line. You can omit the curly braces and the return keyword.
const functionName = (parameters) => statement;
functionName(args);
Example
const add5 = (x) => x + 5;
add5(10); // returns 15

Strings

  • Strings are a sequence of characters surrounded by single (or double) quotes: 'text'
  • String is a primitive data type: typeof "Some text"; // returns 'string' 

Template Literals

  • Template literals use backticks instead of quotes: `text`
  • Template literals allow you to insert JavaScript expressions inside ${expression}
  • Template literals can span multiple lines.
Example
const name = 'Joey';
const age = 22;
`My name is ${name}.
I am ${age} years old.`

String methods

There are a number of methods that can be applied by chaining them to the string.
  • str.toUpperCase() changes the string to uppercase.
  • str.toLowerCase() changes the string to lowercase.
Examples
const name = 'Joey';
let username = name.toLowerCase(); // returns "joey" username = name.toUpperCase(); // returns "JOEY" name; // returns "Joey". The original variable does not change.

Concatenate strings

  • The + operator concatenates stings together: 'text' + 'other text';
  • The concat method also concatenates stings together. 'text'.concat('other text');
Examples
let str = 'Hello ' + 'world';
str; // Returns "Hello world"

let str2 = 'Hello ';
str2.concat('world'); str2; // Returns "Hello world" 

Objects

  • An object is an unordered collection of properties written as name:value pairs.
  • Object is one of JavaScript's eight data types, the only one that is not a primitive type.
  • Preferred way to create an object outside of a class is by declaring an object literal.
const objName = {
  prop1: value,
  prop2: value,
};
    • Object literals are surrounded by curly braces. 
    • Assign it to a const variable unless you plan to reassign the variable.
    • Properties are like variables, listed as name-value pairs separated by commas.
Example
  • Below is an object literal named author. It has four properties of different data types: name (a string), age (a number), active (a boolean), and books (an array).
const author = { 
  name: 'Joey R', 
  age: 34,
  active: true,
  books: ['Learn JavaScript', 'Learn Node.js', 'Learn Express'],
};
Property value shorthand:
  • If the property value is assigned to a variable of the same name, instead of propName: varName } you can use property value shorthand:  { propName }
Example
  • Below are variables for name and age. 
const name = 'Joey R';
const age = 34;
  • Create an object with properties called name and age set to the variables name and age:
const author = { name: name, age: age };
  • Repeat the above using property value shorthand:
const author = { name, age };

Classes

  • Use classes to create multiple objects with the same property names and methods. 
  • JavaScript is object oriented but uses prototypes to create objects instead of classes. 
  • In 2015 class syntax was added to enforce class-like behavior. 
  • A JS class is a special function, called a constructor, that generates new objects. 
  • It is a template that defines the properties and methods for all instances of the class:
class ClassName {
  constructor(prop1, prop2) {
    this.prop1 = prop1;
    this.prop2 = prop2;
  }
}
const instance1 = new ClassName(val1, val2);
    • Declare a class with the class keyword and the class name. 
    • By convention, class names are singular and capitalized / UpperCamelCase.
    • Then add a constructor function with parameters for the object property values.
    • Keyword this refers to the instance object you are creating. 
  • To instantiate an object: 
    • Call the class with the new operator, passing in the property values as arguments. 
    • The class will return a new object. Assign it to a variable.
Example
Create an Author class:
class Author {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
const author1 = new Author('Joey', 32);
  • The constructor function has parameters for name and age.
  • In the last line we instantiate a new object by calling the Author class with the new operator, passing in arguments 'Joey' and 32 for the name and age property values. We assign the new object to variable author1.
Get and set instance properties
  • Access property values by chaining the property name to the object: obj.prop;
  • Set property values with the equals assignment operator: obj.prop = value;
Examples
Get the name property value from the author1 object:
author1.name; // Returns "Joey"

Set the age property value of the author1 object to 33:
author1.age = 33;
author1.age; // Returns 33
Instance methods
  • Instance methods are functions that are applied to a specific instance of a class.
class ClassName {
  constructor(prop1, prop2) {
    this.prop1 = prop1;
    this.prop2 = prop2;
  }
  method1() { statements; };
  method2() { statements; };
} const instance1 = new ClassName(val1, val2); instance1.method1();
    • Put instance methods after the constructor.
    • Method Syntax: methodName() { statements; }
    • Keyword this references the current object.
      • Example: Add 1 to the object's age value: addYear() { this.age += 1; }
  • Call the method by chaining it to an instance object: obj.methodName()
Example
  • Create an Author class that sets name and age properties and instance methods to add a year to the age value and logs information about the author. 
class Author {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  addYear() { this.age += 1; };
  log() { return `${this.name} is ${this.age} years old.` };
}

  • Instantiate an Author object and assign it to the variable author1.
  • Then call author1.add() which changes the age property value to 33.
  • Then call author1.log() which returns information about the author1 object.
const author1 = new Author('Joey R', 32);
author1.addYear();
let view = author1.log(); // returns Joey R is 32 years old.

Arrays

  • JS arrays are list-like objects that store multiple values, called elements, in a variable.
  • You can create an array literal using the array operator "[]".
    • const arr = ['elem1', 'elem2', 'elem3'];
  • Assign arrays to const variables unless you need to reassign the variable.
  • Elements have index numbers starting with 0.
  • Arrays can change length and the elements can be of one or more data types.
  • Arrays are not their own datatype. They are a type of object: typeof []; // returns 'object'
Get and Set Array Elements
  • Get an array element's value with its index number: arr[i];
  • Get the last element by subtracting 1 from the array length: arr[arr.length - 1];
  • Change an element value: arr[i] = value;
Examples
  • Create an array of three fruit names. Then get the elements by their index number.
const arr = ['apple', 'banana', 'orange'];
arr[0]; // returns 'apple' arr[1]; // returns 'banana' arr[2]; // returns 'orange'

Get the last element:
arr[arr.length - 1]; // returns 'orange'

Change the value of the second array element to "blackberry":
arr[1] = 'blackberry';
arr[1]; // returns 'blackberry'
Add or remove elements from the start or end of the array
  • arr.shift(); Removes an item from the front of the array and returns it.
  • arr.unshift(); Adds an item to the front of the array.
  • arr.pop() Removes an item from the front of the array and returns it.
  • arr.push() Adds an item to the end of the array.
Examples
const arr = ['a', 'b', 'c'];

  • Remove an item from the front of the array and return it.
let elem = arr.shift(); // arr is now ['b', 'c']
elem; // returns 'a'

  • Add an item to the front of the array.
arr; // returns ['b', 'c']
arr.unshift(1); // arr is now [1, 'b', 'c']

  • Remove an item from the front of the array and return it.
arr; // returns [1, 'b', 'c']
let elem = arr.pop(); // arr is now [1, 'b']
elem; // returns 'c'

  • Add an item to the end of the array.
arr; // returns [1, 'b']
arr.push(3); // arr is now [1, 'b', 3']
Iterate over an array
  • arr.forEach(); Iterates over each item in the array.
  • Takes a callback function as its argument to perform some operation on each element.
Example
  • Iterate through the array and log each element to the console. 
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.forEach((elem) => {
  console.log(elem);
});

JavaScript: DOM-related Web APIs

JavaScript has properties and methods to interact with a web page.
Terms: DOM, API, DOM-related Web APIs
  • Document Object Model (DOM): When an HTML document is sent by a server to the web browser, the browser converts it to an object called the Document Object Model, or the DOM. 
  • API: An API (Application Programming Interface) is an interface for a program to interact with a separate software component or resource. The API can provide data, functions, routines or other services to your program. 
  • DOM-related Web APIs: The browser has APIs that provide an interface between JavaScript and the DOM. There are JavaScript properties and methods to access, create, move and change HTML elements on the web page. Event listeners can be added to elements that get triggered when a given event occurs.

Script Element

<script src="fileName.js" defer></script> //Place script element in the document head elem.
Defer attribute
  • The defer attribute causes the browser to load the JavaScript file in parallel with parsing the HTML document, thus speeding up the process. 
  • Defer then executes the script after the HTML document has been parsed, but before the DOMContentLoaded event is fired.

Web APIs for manipulating a web page

In the web page assign ids to the elements you want to access:
  • <button id="id">...</button>
Get elements from the HTML document
At the top of the script, select the elements you will access by their ids:
  • const elem = document.getElementById('id'); //Finds the first element that matches the id.
Examples
Below is the body of an HMTL document. The elements we want to access have Ids.
<body>
  <h1 id="heading" class="light-theme">Try JS</h1>
  <button id="btn">Clickme</button>
  <ul id="list"></ul>
</body>

At the top of the JavaScript file get the elements with ids "heading", "btn" and "result":
const heading = document.getElementById('heading');
const btn = document.getElementById('btn');
const list = document.getElementById('list');
Get or set element content
  • Get or set text content: textContent is for text only:
    • elem.textContent; // Gets the text content of the element.
    • elem.textContent = 'New text content'; // Sets new text content.
  • Get or set innerHTML: can include text and/or other HTML elements:
    • elem.innerHTML; // Gets the element's inner HTML content.
    • elem.innerHTML = 'New HTML content'; // Sets new inner HTML content.
Examples
Log the text content of the heading element, then reset the value.
console.log(heading.textContent); // logs "Try JS"
heading.textContent = "Try JS code snippets";

Set the content of the heading that includes text and an HTML element.
heading.innerHTML = "Try JS <small>enter code snippets</small>";
heading.innerHTML; // returns "Try JS <small>enter code snippets</small>"
Insert a list from a JavaScript array:
  • Create an empty list element in the HTML document. Assign an id to it.
<ul id="listId"></ul>
  • Populate the list element on the web page with list items from an array:
const listElem = document.getElementById('listId'); // Get the element.
...
const arr = getDataArray(); //Get data array from a source like a database.
let listItems = ''; //Set an empty string variable to hold the list items.
arr.forEach((item) => { // Iterate over the array, passing in each item.
  listItems += `<li>${item}</li>`; //Put it in li tags, append to listElem.
});
listElem.innerHTML = listItems;
Example
  • Put an empty list element in the HTML document:
<ul id="list"></ul>

  • Populate the list element on the web page with list items from an array:
const list = document.getElementById('list');
...
const arr = ['Item 1', 'Item 2', 'Item 3'];
let listItems = '';
arr.forEach((item) => {
  listItems += `<li>${item}</li>`; 
});
list.innerHTML = listItems;
    • Get the list element in the script.
    • Get the array. In a real app this would probably come from a database. For this example we are just using an array literal. 
    • Create an empty variable named listItems.
    • Create an array name arr. Iterate over it using the forEach method. 
      • Put each item from the array into an li (list item) HTML element. 
      • Append the li element to the listItems string variable. 
    • When all items from the array are appended to the listItems string, set the list element's innerHTML property to the listItems string. This will display the list on the web page. 
Class List
Change the styling of an element by adding or removing classes:
  • elem.classList.contains('class'); //Check if elem contains the class. Returns true/false.
  • elem.classList.add('class1'[, 'class2',...]);  // Adds the class or classes to the element.
  • elem.classList.remove('class1'[, 'class2',...]); // Removes the class(es) from the element.
  • elem.classList.toggle('class1'); // Toggle (add/remove) the given class.
Example
  • The HTML document has a heading element with class "light-theme".
<h1 id="heading" class="light-theme">Try JS</h1>
  • Put light-theme and dark-theme classes in the stylesheet/styles.css file.
.light-theme { background-color: whitesmoke; color: black; }
.dark-theme { background-color: black; color: white; }
  • In the JavaScript file get the heading element. Remove the light-theme class and add the dark-theme class. This will change the class when the page is first loaded.
const heading = document.getElementById('heading');
...
heading.classList.remove('light-theme');
heading.classList.add('dark-theme');

Events

Listen for and respond to events on the page such as a button click:
  • targetElem.addEventListener('eventType', handlerFunction); // Listen for a specific event 
    • targetElement is the element the event occurs on, such as a button element.
    • eventType is the event you are listening for such as a "click" event.
    • HandlerFunction: is the function that executes with the event is triggered.
Common events include:
  • Mouse click events: "click" or "dblclick": User clicks or double-clicks an element.
  • Mouse hover events: "mouseover": The user hovers the mouse over an element.
  • Keyboard events: "keydown": The user presses a specific key.
  • Form events: 
    • "focus": The user clicks in a form field. 
    • "blur": the user clicks outside the form field. 
    • "change": the user changes the value in a form field. 
    • "submit": the user clicks the submit button. 
  • Window events: "DOMContentLoaded": Web page finishes loading main components.
Example
  • In the HTML document add a button with id "btn".
<button id="btn">Clickme</button>

  • In the attached JavaScript file get the element with id btn, listen for the "click" event, and log a message when the event is triggered.
const btn = document.getElementById('btn');
...
btn.addEventListener('click', () => {
  console.log('Button was clicked');
});

Node.js Express Web Framework

Generate a basic app

Express Generator: expressjs.com/en/starter/generator.html
Generate an express app with express generator: npx express-generator appName --view=ejs 
Install the dependencies: npm install

Run/Stop the development server

Run the development server: npm start
Open a browser tab and go to: http://localhost/3000
Stop the development server: Control+C

Header and Footer partials

view/header.ejs
<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link href="/images/faviconImageFile" rel="icon" type="image/x-icon">
    <link rel='stylesheet' href='/stylesheets/style.css'>
  </head>
  <body>
    <nav>...</nav>
    <main>
views/footer.ejs
    </main>
    <footer>...</footer>
  </body>
</html>
Insert header and footer partials
views/filename.ejs
<%- include('header') %>
/* Put main content here */
<%- include('footer') %>

Install Sqlite Database and Sequelize ORM

  • Install the Sqlite3 and Sequelize dependencies: npm install sqlite3 sequelize
  • Generate the general model files: npx sequelize-cli init > Agree to the prompt: y 
  • Change the config/config.json file to:
{
  "development": {
    "dialect": "sqlite",
    "storage": "./database.sqlite3"
  }
}
  • Generate model: npx sequelize-cli model:generate --name ModelName --attributes attribute:dataType[,attrib:type...] 
  • Create the database: npx sequelize-cli db:migrate 
Generate Article model example:
  • Generate a model called Article with attributes and datatypes of title: string, content: text.
npx sequelize-cli model:generate --name Article --attributes title:string,content:text 

Routes and EJS files

Index/List - Route

routes/index.js
const express = require('express');
const router = express.Router();
const { Collection } = require('../models');
const createError = require('http-errors');
 
// Routes
router.get('/', list);
router.get('/create', createForm);
router.post('/create', create);
router.get('/:id', detail);
router.get('/:id/update', updateForm);
router.post('/:id/update', update);
router.get('/:id/delete', destroy);

// Controller Functions
// GET
async function list(req, res, next) {
  const collections = await Collection.findAll({ 
    attributes: ['id', 'mainField', 'createdAt'],
    order: [['fieldToSortBy', 'DESC']] // ASC or DESC
  })
  res.render('index', { title: 'Title', collections });
}

// detail handler function goes here.
// createForm handler function goes here.
// create handler function goes here.
// updateForm handler function goes here.
// update handler function goes here.
// destroy handler function goes here.

module.exports = router;
Index/List - View
views/index.ejs
<%- include('header') %>

<h1>
  Collections <a href='/create'>Create new collection</a>
</h1>
<ul>
  <% collections.forEach((collection) => { %>
    <li>
      <a href="/<%= collection.id %>"><%= collection.mainField %></a>
    </li>
  <% }); %>
</ul>

<%- include('footer') %>

Detail - Route

routes/index.js
async function detail(req, res, next) { 
  const collection = await Collection.findByPk(req.params.id);
  if (!collection) {
    return next(createError(404));
  }
  res.render('detail', { title: 'Collection', collection });    
}
Detail - View
views/detail.ejs
<%- include('header') %>

<h1>
  <%= collection.mainField %>
  <a href="/<%= collection.id %>/delete">Delete</a>
  <a href="/<%= collection.id %>/update">Edit</a>
</h1>
<p>
  <strong>Date:</strong>
  <%= collection.updatedAt.toLocaleString("en-US", 
   { month: 'long', day: 'numeric', year: 'numeric' }); %>
</p>

<hr class='mt-2'>

<div><%= collection.field2 %></div>
<div><%= collection.field3 %></div>

<%- include('footer') %>

Create - Routes

routes/index.js
function createForm(req, res, next) {
  res.render('create', { title: 'Create Collection' });
}
 
async function create(req, res, next) {
  const collection = await Collection.create(req.body, {fields: ['mainField', 'field2', 'field3'] });
  res.redirect(`/${collection.id}`);    
}
Create - View
views/create.ejs
<%- include('header') %>

<h1>Create Collection</h1>
<hr>
<form method="POST" action="">
  <div>
    <label for="mainField">MainField</label>
    <input type="text" id="mainField" name="mainField">
  </div>
  <div>
    <label for="field2">Field2</label> <input type="text" id="field2" name="field2"> </div> <div> <label for="field3">Field3</label> <input type="text" id="field3" name="field3"> </div> <button type="submit">Submit</button> </form> <%- include('footer') %>

Update - Route

routes/index.js
async function updateForm(req, res, next) { 
  const article = await Collection.findByPk(req.params.id);
  res.render('update', { title: 'Update Collection', collection });    
}
 
async function update(req, res, next) {
  const id = req.params.id; 
  await Collection.update(req.body, {where: {id: id}, fields: ['mainField', 'field2', 'field3'] });
  res.redirect(`/${id}`); 
Update - View
views/update.ejs
<%- include('header') %>

<h1>Update Collection</h1><hr>

<form method="POST" action="">
  <div>
    <label for="title">MainField</label><br>
    <input type="text" id="mainField" name="mainField"
           value="<%= collection.mainField %>">
  </div>

  <div>
    <label for="field2">Field2</label><br>
    <input type="text" id="field2" name="field2"
           value="<%= collection.field2 %>">
  </div>

  <div>
    <label for="field3">Field3</label><br>
    <input type="text" id="field3" name="field3"
           value="<%= collection.field3 %>">
  </div>

  <div>
    <button type="submit">Submit</button>
    <a href="/<%= collection.id %>">Cancel</a>
  </div>
</form>

<%- include('footer') %>

Delete - Route

routes/index.js
async function destroy(req, res, next) {
  await Collection.destroy({where: {id: req.params.id}});
  res.redirect('/');   
}