Programming the Cloud

Programming the Cloud (PtC) is a reference for learning-by-example the following:

  1. Front end web technologies (HTML, CSS and JavaScript).
  2. Full-stack architecture design.
  3. Implementing backend servers using Node.js.
  4. Administrating and programming mongoDb databases.
  5. Building apps using Cordova, Capacitor and Electron.
  6. Advanced JS concepts like the event-model, anonymous functions, callbacks etc.
  7. Program internet/bluetooth enabled microcontrollers (focus on esp32).
  8. Design/implement Voice UI for Amazon Echo, Google Nest etc.
.... and much, much more.

PtC is free and open source, you can find the source code on GitHub. Issues and feature requests can be posted on the GitHub issue tracker.

Organization

PtC is organized into 4 broad sections.

  • Section 1 teaches you the preliminary concepts and basic skills.
  • Section 2 discusses front end technologies such as HTML, CSS, JS, jQuery, JSON.
  • Section 3 completes our discussion on full-stack programming by covering back-end technologies such as servers, databases, managing IaaS, scaling etc.
  • Section 4 covers how to write client and server programs on microcontrollers thus enabling us to connect everyday objetcs to the Internet (an emerging field called the Internet-of-Things (IoT)).

License

"Programming the Cloud" book, all the source code, is released under the GNU General Public License v2.

Preliminaries

In this section we will develop a concept map and vocabulary that will serve as a foundation for our discussion throughout this guide. We will first discuss the Client-Server Model; then learn where in the "Programmer's model" of a computer these client and server programs reside. We finally learn how these client-server programs communicate with each other over the Internet using URLs.

By the end of this section you should have a working definition and a concept map interlinking the following terms:

  • Client
  • Server
  • Computer
  • Program
  • Programmer's Model
  • Port
  • IP address
  • URL
  • Internet
  • OSI Model
  • HTTP
  • HTTP request
  • HTTP response

The Client Server Model

The world wide web is build on top of the client server model. The client server model consists of clients and servers that communicate with each other. There are 2 rules in the client server protocol:

  1. The client initiates contact with the server by sending a request.

  2. The server (whose job is to listen to these client requests), processes the request and then sends a response back.

Fig: 1.1.1.1. The Client Server Model

The server is an application program and can hence respond differently based on the request URL's path. For Eg: the URLs https://google.com and https://google.com/maps both send a request to google.com, but based on the path (if it has "/maps" or not) a different page is served.

Programming Model of a Computer

We now know that clients and servers are programs that communicate with one another according to the client-server model. But where within the nodes of the Internet (computers, phones, tablets) do clients and servers exist?.

Fig: 1.2.1. Programming model of a Computer

Clients and servers are applications that reside in the application layer of a computer (see Figure above). For eg. YouTube.com is a server which can be accessed via a web browser (on computers and phones) or apps (also on computers and phone). Other examples include GitHub.com, Slack, Facebook, Google etc. All these "Internet Software" have a server and client apps as part of their ecosystem. Developing and maintaining these is referred to as devops (Developer Operations).

This guide focusses on train you in devops for Internet Software development. Section 4 of the guide deals with deploying clients and servers on Microcontrollers (small bare bones computers with no OS, but programmable firmware).

The Internet

We all have a working definition of what Internet means to us. However, just like there are different ways to visualize a computer (as seen in last section), the Internet can defined from different perspectives. These definitions are related by a hierarchy called the Open Systems Interconnection (OSI) Model.

Fig: 1.1.3.1. OSI Model of Internet

To learn more about the OSI model please read this: https://en.wikipedia.org/wiki/OSI_model

Uniform Resource Locator (URL)

The URL encodes request data that the client sends to a server. The client addresses the server and embeds all other parameters of the request in a URL. The Figures below shows an example of a URL, and components that make up a URL.

Fig: 1.4.1 URL example
Fig: 1.4.2 Parts of a URL

The URL provides the following basic information in order to route the request to the right server:

  1. Protocol scheme (http or https in case of websites/apps).
  2. IP address (or DNS name which resolves to an IP address), which is unique to every computer including servers.
  3. Port. This allows request to be sent to different server programs on the same computer. Hidden in case of http/https and defaults to 80/443.
  4. Path, invoking the right request handler in the server.
  5. A query string that provides arguments to the request handler in key-value pairs.

Routing these request correctly is what makes youtube.com respond with the video. Depending on the video ID (argument v) a different video is served. A playlist is displayed if a valid list argument is present. Try opeing the following 2 urls:

  1. https://www.youtube.com/watch?v=BKo3SBfjiX4&list=PLbpi6ZahtOH4iOdBSB7PLd079Nw9-2ep4
  2. https://www.youtube.com/watch?v=BKo3SBfjiX4

Can you notice the difference?

The Figure below shows the parts of a generic URL.

Fig: 1.4.3 URL Grammar

Basic Skills

This section covers the basic skills needed to follow along the examples in this guide. If unfamiliar using the command line the section on Bash will introduce you to the BASH shell. This shell is available on all major operating systems -- Linux, Mac OS and Windows, via git-bash. Once we have some familiarity with the command line, we will learn to use GIT for managing our code. The chapter ends with a discussion on code editors and how to deploy code on remote machines.

Using BASH

Bash is available by default on Mac and Linux and can be access via git-bash (installed when git is installed) on Windows. Bash is a "command line interpreter" meaning that it awaits your commands, usually one line at a time and executes them.

You know you are in a bash shell if you see a dollar ($) prompt with a blinking cursor awaiting your command.

Once you are at the bash prompt, you can find out who you are by typing $ whoami

This will print your username.

Next we can find out where in the filesystem we are by typing $ pwd

This will print the present working directory (within file system).

Here are some other basic commands to try out

  1. $ ls List the contents of the present working directory. You can also

    • $ls -a : lists all files including hidden ones.
    • $ls -l : list files with details
  2. $ cd <directory path> Change directory. If no directory name is specified then present working directory is set to your $HOME.

  3. $ cat <filename> Prints the content of file <filename>.

  4. $ man <command> Prints the manual for <command>.

Reference of basic commands

Use $man <command> to learn more about these commands and flags.

basic shell

  • clear : clear all previous commands' output text from the terminal
  • exit (or logout) : quits the shell
  • history : show a list of all past commands you have typed into this shell

manage directories

  • ls : list files in a directory
  • pwd : displays the shell's current working directory
  • cd : changes the shell's working directory to the given directory; can be a relative or absolute path
  • mkdir : creates a new directory with the given name
  • rmdir : removes the directory with the given name (the directory must be empty)

file operations

  • cp : copies a file/directory
  • mv : moves (or renames) a file/directory
  • rm : deletes a file
  • touch : update the last-modified time of a file (or create an empty file)
  • cat : output the contents of a file
  • more (or less) : output the contents of a file, one page at a time
  • head, tail : output the beginning or ending of a file
  • wc : output a count of the number of characters, lines, words, etc. in a file
  • du : report disk space used by a file/directory
  • diff : output differences between two files
  • chmod : change the permissions on a file or group of files
  • chown : change the owner of a file
  • chgrp : change the group associated with a file
  • umask : change the default permissions given to newly created files

searching and sorting

  • grep : search a file for a given string or expression
  • sort : convert an input into a sorted output
  • uniq : strip duplicate lines
  • find : search for files by name within a given directory
  • xargs : launch a command over each of a set of lines of input (often used with find)
  • locate : search for files by name on the entire system
  • which : shows the complete path of a command or file

compression

  • zip, unzip : create a .zip archive or extract its contents
  • tar : Unix archiving/de-archiving program
  • gzip, gunzip : GNU compression/decompression programs
  • bzip2, bunzip2 : improved compression/decompression programs

system information

  • date : outputs the current date/time
  • cal : outputs an ASCII calendar
  • uname : print information about the system
  • time : measure how long a program takes to run

process management

  • ps, jobs : list the processes you are running; every process has a unique integer id number (PID)
  • top : see what processes are using the most CPU/memory, and show system memory/CPU stats
  • kill : terminate a process
  • killall : terminate a group of processes by name
  • ^C: (hotkey) terminates (kills) the currently running process
  • ^Z : (hotkey) suspends the currently running process
  • & : (special character) when & is placed at the end of a command, that command is run in the background (shell does not wait for the command to finish before returning to the input prompt)

users

  • whoami : outputs your user name
  • passwd : changes your password
  • groups : list the groups to which a user belongs
  • sudo : execute a single command as the super-user
  • su : log in to a shell as the super-user

network

  • lynx : text-only web browser
  • ssh : connect to a remote Unix server
  • wget : download from a URL and save it to a file on the local hard drive
  • curl : download from a URL and output its contents to the console

text editors

  • vi, vim : good command line editor
  • emacs : a complicated text editor with a steep learning curve

programming

  • node : run a JavaScript program, or enter JS shell
  • javac, java, python, perl, ruby, gcc, sml, ... : compile or run programs in various other languages

Node.js

Node.js is a JavaScript Interpreter. In fact it is the same Interpreter found in Chrome (V8). Node.js however is used to write servers and desktop (command line) software.

Installation

Download the lastes version: https://nodejs.org/en/

Install using the installer. On Mac OS if you are blocked (unidentified developer etc.) Go to System Preferences -> Security & Privacy -> General and click on the button Open Anyway.

Once the installation is complete you can use Node.js in Bash. Type:

$ node

To enter the JS shell.

To execute(interpret) a JS file:

$ node <filename.js>

To install node modules/packages:

$ npm install <package_name>

http-server

http-server is a command line server tool. It can turn any folder into a static http-server. Once executed it prints out the URL where your files can be accessed over http.

To install

$ npm install http-server

To use

$ http-server <folder_path>

If no folder is specified then the pwd will be used.

You can also specify port number as:

$ http-server <folder_path> -p <port_no>

Browser Developer Tools

In order to bring up the development tools, right-click anywhere on the html document. You should be able to choose inspect from the context menu that appears.

Fig: 2.1.1.1. Trigger inspector for contect menu (right-click)
Fig: 2.1.1.2. Developer Tools

Using GIT

Motivation

Why use Git? If you are interested in doing any/all of the following

  1. Use GIT for maintaining your code/design project files.
  2. Collaborate with teammates over the cloud (think Google docs but for project files).
  3. Better than backups: https://git-scm.com/book/en/v2/Getting-Started-What-is-Git%3F (GIT stores entire files that have been changed -- see Figure below. For each version of GIT we have to manually "stage" the changed files to be tracked.
Fig: 2.4.1. Traditional Version Control System vs. GIT
  1. Publish/access open source code.

This guide teaches you step-by-step how to get started with github, or other flavors of git (using the command line).

Installation

Mac OS:

  1. Open terminal.

  2. $ git --version

    If you see output like:

    git version 2.20.1 (Apple Git-117); Git is installed.

    Otherwise you will be prompted to install xcode tools. Please follow steps to install these.

Linux

In console

$ sudo apt install git.

Windows

Download Installer

https://git-scm.com/download/win

Please install git-bash as well. We will assume you are using git-bash to execute bash commonds on Windows.

Lifecycle

The git lifecycle includes creating versions ("commits") of your development folder as and when it changes. You will "add" files to be "tracked" in your folder by the git add command. You stage the added files for a "commit" (version) by using the git commit. If your repository is maintained on the cloud, you will need git push to sync the new version created with your cloud (remote) repository.

Fig: 2.4.2. GIT Lifecycle

You can create a remote repository by hosting your own git server, or use Git-as-a-Service(GaaS) providers like GitHub, GitLab, Bitbucket etc. The following tutorial uses Github as GaaS, but the command-line steps should work the same with any GaaS.

Step-by-step

  1. Create a Github account
  2. Create a Github Repo
Fig: 2.4.3. Create new repository
  1. Find repo url
Fig: 2.4.4. Clone repository
  1. Clone repo $ git clone <yout repo-url> This will create a folder with the repo name and "checkout" the lastest commit.

  2. cd to new folder created, you can now add/edit delete/files from this folder.

  3. To create new commit $ git add * $ git commit -m "<your-message>"

  4. To sync your repo with cloud repo $ git push

  5. Continue editing your project files and to create a new version use git commands add -> commit -> push (Figure 2.4.2).

GIT Command Reference

  • git config : set your user name and email.
  • git init : initialise a git repository.
  • git clone : close your git repo.
  • git status : status of git repo
  • git add : stage files for commit
  • git commit : create commit. use -m flag to ad message (recommended)
  • git push : sync local commits to remote repo.
  • git pull : sync remote commits to local clone.

Editing Code

The examples in this guide will need you to edit code/document format files (HTML, CSS, JS, C++ etc.). You can use any editor you are comfortable with. It is recommended that you use an editor with syntax highlighting.

Here is a list of recommended code editors

The first 4 are visual editors with a simple to use, with a user-friendly GUI. VI and EMACS on the other hand are command-line (Bash) editors. These will come in handy when you need to edit on a remote machine. However both have steep learning curves and will take practice to perfect. If you are new to programming this guide suggests you start with Atom Editor (first choice in the above list). It has a tabbed editor and a project manager pane (Figure 2.5.1). You can easily add new files, manage folders and edit/modify/save individual files.

Fig: 2.5.1 Atom Editor

Code Deployment

Some of the code examples (usually server or db management) need to be deployed on a remote machine provisioned by you (you can provision such machines using IaaSs like Amazon Web Services, Google Cloud Compute, Ali Yun, Microsoft Azure and others).

When you provision a Linux machine on these remote servers you only have shell access via SSH. In such circumstances use a cloud git repository to transfer your development code to the remote server. The figure below sketches this workflow.

Fig: 2.6.1. Deploy server code to IaaS server

HTML

Hypertext markup language (HTML) is the lingua franca of the World Wide Web (www). It is also a medium for designing websites and apps. It is however NOT a programming language. Then what is HTML? IT is a document format much like pdf. You can create documents using HTML, style them using CSS (a sub-set of HTML). But such pages will lack interaction (like a pdf document). Interactivity can be added by adding JavaScript to HTML. More on this later.

HTML can be rendered by Browsers like Chrome, Firefox and Safari. In order to edit html files however we will need a text editor (see Figure below). It is convenient to use code editors for this purpose as they provide syntax highlighting, autocomplete, lint and other tools.

Fig: 2.1.1. HTML Source and Output

There are 2 main concepts in HTML Tags and Attributes.

Tags

Tags are used to mark up content; this is where "markup language" in HTML's acronym comes from. HTML is only one of the many markup languages, and definitely the most popular one. In recent years a new open standard for HTML is being created. This is called HTML5. Everything discussed in here is current with this latest version of HTML.

A HTML tag has 3 parts

  1. Start of Tag, written with the tag name within angle brackets
  2. Content -- any valid html
  3. End of Tag -- similar to start but the tag name has a forward slash (/) prefix.
<TAG_NAME>

      content

</TAG_NAME>

Let us start by writing out first HTML.

<!doctype html>

<html>
<head>
  <title> Hello World </title>
</head>
</body>
  <h1> Hello World </h1>
</body>
</html>

The first line in every html document is the <doctype> tag. This tag is stand alone (i.e. does not need to closed as it does not have content). It is meta data to the browser that the file is an HTML file (browsers rely on the file extension and also the <doctype> tag to determine if valid html was served. However most browsers are forgiving if you forget the <doctype> tag.

Editing/ Viewing

Copy the above code and paste it into a new file (use atom if you don't have a favorite code editor). Save the file as index.html. Serve this file using http-server and open the URL in a browser. Notice the title of the browser tab -- it was what we set (Hello World) as the content of the title tag. Try changing it and see it change in the browser.

Tag Reference

Taken from MDN web docs. Please contribute if you can.

Main root

Element Description
<html> The HTML <html> element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element.

Document metadata

Metadata contains information about the page. This includes information about styles, scripts and data to help software (search engines, browsers, etc.) use and render the page. Metadata for styles and scripts may be defined in the page or link to another file that has the information. 

Element Description
<base> The HTML <base> element specifies the base URL to use for all relative URLs in a document.
<head> The HTML <head> element contains machine-readable information (metadata) about the document, like its title, scripts, and style sheets.
<link> The HTML External Resource Link element (<link>) specifies relationships between the current document and an external resource. This element is most commonly used to link to stylesheets, but is also used to establish site icons (both "favicon" style icons and icons for the home screen and apps on mobile devices) among other things.
<meta> The HTML <meta> element represents metadata that cannot be represented by other HTML meta-related elements, like <base>, <link>, <script>, <style> or <title>.
<style> The HTML <style> element contains style information for a document, or part of a document.
<title> The HTML Title element (<title>) defines the document's title that is shown in a browser's title bar or a page's tab.

Sectioning root

Element Description
<body> The HTML <body> Element represents the content of an HTML document. There can be only one <body> element in a document.

Content sectioning

Content sectioning elements allow you to organize the document content into logical pieces. Use the sectioning elements to create a broad outline for your page content, including header and footer navigation, and heading elements to identify sections of content.   

Element Description
<address> The HTML <address> element indicates that the enclosed HTML provides contact information for a person or people, or for an organization.
<article> The HTML <article> element represents a self-contained composition in a document, page, application, or site, which is intended to be independently distributable or reusable (e.g., in syndication).
<aside> The HTML <aside> element represents a portion of a document whose content is only indirectly related to the document's main content.
<footer> The HTML <footer> element represents a footer for its nearest sectioning content or sectioning root element. A footer typically contains information about the author of the section, copyright data or links to related documents.
<header> The HTML <header> element represents introductory content, typically a group of introductory or navigational aids. It may contain some heading elements but also a logo, a search form, an author name, and other elements.
<h1>, <h2>, <h3>, <h4>, <h5>, <h6> The HTML <h1><h6> elements represent six levels of section headings. <h1> is the highest section level and <h6> is the lowest.
<hgroup> The HTML <hgroup> element represents a multi-level heading for a section of a document. It groups a set of <h1>–<h6> elements.
<main> The HTML <main> element represents the dominant content of the <body> of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.
<nav> The HTML <nav> element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes.
<section> The HTML <section> element represents a standalone section — which doesn't have a more specific semantic element to represent it — contained within an HTML document.

Text content

Use HTML text content elements to organize blocks or sections of content placed between the opening <body> and closing </body> tags.

Element Description
<blockquote> The HTML <blockquote> Element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation (see Notes for how to change it). A URL for the source of the quotation may be given using the cite attribute, while a text representation of the source can be given using the <cite> element.
<dd> The HTML <dd> element provides the description, definition, or value for the preceding term (<dt>) in a description list (<dl>).
<div> The HTML Content Division element (<div>) is the generic container for flow content. It has no effect on the content or layout until styled using CSS.
<dl> The HTML <dl> element represents a description list. The element encloses a list of groups of terms (specified using the <dt> element) and descriptions (provided by <dd> elements). Common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs).
<dt> The HTML <dt> element specifies a term in a description or definition list, and as such must be used inside a <dl> element.
<figcaption> The HTML <figcaption> or Figure Caption element represents a caption or legend describing the rest of the contents of its parent <figure> element.
<figure> The HTML <figure> (Figure With Optional Caption) element represents self-contained content, potentially with an optional caption, which is specified using the (<figcaption>) element.
<hr> The HTML <hr> element represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section.
<li> The HTML <li> element is used to represent an item in a list.
<main> The HTML <main> element represents the dominant content of the <body> of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.
<ol> The HTML <ol> element represents an ordered list of items — typically rendered as a numbered list.
<p> The HTML <p> element represents a paragraph.
<pre> The HTML <pre> element represents preformatted text which is to be presented exactly as written in the HTML file.
<ul> The HTML <ul> element represents an unordered list of items, typically rendered as a bulleted list.

Inline text semantics

Use the HTML inline text semantic to define the meaning, structure, or style of a word, line, or any arbitrary piece of text.

Element Description
<a> The HTML <a> element (or anchor element), with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address.
<abbr> The HTML Abbreviation element (<abbr>) represents an abbreviation or acronym; the optional title attribute can provide an expansion or description for the abbreviation.
<b> The HTML Bring Attention To element (<b>)  is used to draw the reader's attention to the element's contents, which are not otherwise granted special importance.
<bdi> The HTML Bidirectional Isolate element (<bdi>)  tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text.
<bdo> The HTML Bidirectional Text Override element (<bdo>) overrides the current directionality of text, so that the text within is rendered in a different direction.
<br> The HTML <br> element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.
<cite> The HTML Citation element (<cite>) is used to describe a reference to a cited creative work, and must include the title of that work.
<code> The HTML <code> element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code.
<data> The HTML <data> element links a given content with a machine-readable translation. If the content is time- or date-related, the <time> element must be used.
<dfn> The HTML Definition element (<dfn>) is used to indicate the term being defined within the context of a definition phrase or sentence.
<em> The HTML <em> element marks text that has stress emphasis. The <em> element can be nested, with each level of nesting indicating a greater degree of emphasis.
<i> The HTML <i> element represents a range of text that is set off from the normal text for some reason.
<kbd> The HTML Keyboard Input element (<kbd>) represents a span of inline text denoting textual user input from a keyboard, voice input, or any other text entry device.
<mark> The HTML Mark Text element (<mark>) represents text which is marked or highlighted for reference or notation purposes, due to the marked passage's relevance or importance in the enclosing context.
<q> The HTML <q> element indicates that the enclosed text is a short inline quotation. Most modern browsers implement this by surrounding the text in quotation marks.
<rb> The HTML Ruby Base (<rb>) element is used to delimit the base text component of a  <ruby> annotation, i.e. the text that is being annotated.
<rp> The HTML Ruby Fallback Parenthesis (<rp>) element is used to provide fall-back parentheses for browsers that do not support display of ruby annotations using the <ruby> element.
<rt> The HTML Ruby Text (<rt>) element specifies the ruby text component of a ruby annotation, which is used to provide pronunciation, translation, or transliteration information for East Asian typography. The <rt> element must always be contained within a <ruby> element.
<rtc> The HTML Ruby Text Container (<rtc>) element embraces semantic annotations of characters presented in a ruby of <rb> elements used inside of <ruby> element. <rb> elements can have both pronunciation (<rt>) and semantic (<rtc>) annotations.
<ruby> The HTML <ruby> element represents a ruby annotation. Ruby annotations are for showing pronunciation of East Asian characters.
<s> The HTML <s> element renders text with a strikethrough, or a line through it. Use the <s> element to represent things that are no longer relevant or no longer accurate. However, <s> is not appropriate when indicating document edits; for that, use the <del> and <ins> elements, as appropriate.
<samp> The HTML Sample Element (<samp>) is used to enclose inline text which represents sample (or quoted) output from a computer program.
<small> The HTML <small> element represents side-comments and small print, like copyright and legal text, independent of its styled presentation. By default, it renders text within it one font-size smaller, such as from small to x-small.
<span> The HTML <span> element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang.
<strong> The HTML Strong Importance Element (<strong>) indicates that its contents have strong importance, seriousness, or urgency. Browsers typically render the contents in bold type.
<sub> The HTML Subscript element (<sub>) specifies inline text which should be displayed as subscript for solely typographical reasons.
<sup> The HTML Superscript element (<sup>) specifies inline text which is to be displayed as superscript for solely typographical reasons.
<time> The HTML <time> element represents a specific period in time.
<u> The HTML Unarticulated Annotation Element (<u>) represents a span of inline text which should be rendered in a way that indicates that it has a non-textual annotation.
<var> The HTML Variable element (<var>) represents the name of a variable in a mathematical expression or a programming context.
<wbr> The HTML <wbr> element represents a word break opportunity—a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location.

Image and multimedia

HTML supports various multimedia resources such as images, audio, and video.

Element Description
<area> The HTML <area> element defines a hot-spot region on an image, and optionally associates it with a hypertext link. This element is used only within a <map> element.
<audio> The HTML <audio> element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the <source> element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a MediaStream.
<img> The HTML <img> element embeds an image into the document.
<map> The HTML <map> element is used with <area> elements to define an image map (a clickable link area).
<track> The HTML <track> element is used as a child of the media elements <audio> and <video>. It lets you specify timed text tracks (or time-based data), for example to automatically handle subtitles. The tracks are formatted in WebVTT format (.vtt files) — Web Video Text Tracks or Timed Text Markup Language (TTML).
<video> The HTML Video element (<video>) embeds a media player which supports video playback into the document. You can use <video> for audio content as well, but the <audio> element may provide a more appropriate user experience.

Embedded content

In addition to regular multimedia content, HTML can include a variety of other content, even if it's not always easy to interact with.

Element Description
<embed> The HTML <embed> element embeds external content at the specified point in the document. This content is provided by an external application or other source of interactive content such as a browser plug-in.
<iframe> The HTML Inline Frame element (<iframe>) represents a nested browsing context, embedding another HTML page into the current one.
<object> The HTML <object> element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin.
<param> The HTML <param> element defines parameters for an <object> element.
<picture> The HTML <picture> element contains zero or more <source> elements and one <img> element to offer alternative versions of an image for different display/device scenarios.
<source> The HTML <source> element specifies multiple media resources for the <picture>, the <audio> element, or the <video> element.

Scripting

In order to create dynamic content and Web applications, HTML supports the use of scripting languages, most prominently JavaScript. Certain elements support this capability.

Element Description
<canvas> Use the HTML <canvas> element with either the canvas scripting API or the WebGL API to draw graphics and animations.
<noscript> The HTML <noscript> element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser.
<script> The HTML <script> element is used to embed or reference executable code; this is typically used to embed or refer to JavaScript code.

Demarcating edits

These elements let you provide indications that specific parts of the text have been altered.

Element Description
<del> The HTML <del> element represents a range of text that has been deleted from a document.
<ins> The HTML <ins> element represents a range of text that has been added to a document.

Table content

The elements here are used to create and handle tabular data.

Element Description
<caption> The HTML Table Caption element (<caption>) specifies the caption (or title) of a table, and if used is always the first child of a <table>.
<col> The HTML <col> element defines a column within a table and is used for defining common semantics on all common cells. It is generally found within a <colgroup> element.
<colgroup> The HTML <colgroup> element defines a group of columns within a table.
<table> The HTML <table> element represents tabular data — that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data.
<tbody> The HTML Table Body element (<tbody>) encapsulates a set of table rows (<tr> elements), indicating that they comprise the body of the table (<table>).
<td> The HTML <td> element defines a cell of a table that contains data. It participates in the table model.
<tfoot> The HTML <tfoot> element defines a set of rows summarizing the columns of the table.
<th> The HTML <th> element defines a cell as header of a group of table cells. The exact nature of this group is defined by the scope and headers attributes.
<thead> The HTML <thead> element defines a set of rows defining the head of the columns of the table.
<tr> The HTML <tr> element defines a row of cells in a table. The row's cells can then be established using a mix of <td> (data cell) and <th> (header cell) elements.

Forms

HTML provides a number of elements which can be used together to create forms which the user can fill out and submit to the Web site or application. There's a great deal of further information about this available in the HTML forms guide.

Element Description
<button> The HTML <button> element represents a clickable button, which can be used in forms or anywhere in a document that needs simple, standard button functionality.
<datalist> The HTML <datalist> element contains a set of <option> elements that represent the permissible or recommended options available to choose from within other controls.
<fieldset> The HTML <fieldset> element is used to group several controls as well as labels (<label>) within a web form.
<form> The HTML <form> element represents a document section containing interactive controls for submitting information.
<input> The HTML <input> element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent.
<label> The HTML <label> element represents a caption for an item in a user interface.
<legend> The HTML <legend> element represents a caption for the content of its parent <fieldset>.
<meter> The HTML <meter> element represents either a scalar value within a known range or a fractional value.
<optgroup> The HTML <optgroup> element creates a grouping of options within a <select> element.
<option> The HTML <option> element is used to define an item contained in a <select>, an <optgroup>, or a <datalist> element. As such, <option> can represent menu items in popups and other lists of items in an HTML document.
<output> The HTML Output element (<output>) is a container element into which a site or app can inject the results of a calculation or the outcome of a user action.
<progress> The HTML <progress> element displays an indicator showing the completion progress of a task, typically displayed as a progress bar.
<select> The HTML <select> element represents a control that provides a menu of options
<textarea> The HTML <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, for example a comment on a review or feedback form.

Interactive elements

HTML offers a selection of elements which help to create interactive user interface objects.

Element Description
<details> The HTML Details Element (<details>) creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state.
<dialog> The HTML <dialog> element represents a dialog box or other interactive component, such as an inspector or window.
<menu> The HTML <menu> element represents a group of commands that a user can perform or activate. This includes both list menus, which might appear across the top of a screen, as well as context menus, such as those that might appear underneath a button after it has been clicked.
<menuitem> The HTML <menuitem> element represents a command that a user is able to invoke through a popup menu. This includes context menus, as well as menus that might be attached to a menu button.
<summary> The HTML Disclosure Summary element (<summary>) element specifies a summary, caption, or legend for a <details> element's disclosure box.

Web Components

Web Components is an HTML-related technology which makes it possible to, essentially, create and use custom elements as if it were regular HTML. In addition, you can create custom versions of standard HTML elements.

Element Description
<content> The HTML <content> element—an obsolete part of the Web Components suite of technologies—was used inside of Shadow DOM as an insertion point, and wasn't meant to be used in ordinary HTML.
<element> The obsolete HTML <element> element was part of the Web Components specification; it was intended to be used to define new custom DOM elements.
<shadow> The HTML <shadow> element—an obsolete part of the Web Components technology suite—was intended to be used as a shadow DOM insertion point.
<slot> The HTML <slot> element—part of the Web Components technology suite—is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together.
<template> The HTML Content Template (<template>) element is a mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript.

Obsolete and deprecated elements

Warning: These are old HTML elements which are deprecated and should not be used. You should never use them in new projects, and should replace them in old projects as soon as you can. They are listed here for informational purposes only.

Element Description
<acronym> The HTML Acronym Element (<acronym>) allows authors to clearly indicate a sequence of characters that compose an acronym or abbreviation for a word.
<applet> The obsolete HTML Applet Element (<applet>) embeds a Java applet into the document; this element has been deprecated in favor of <object>.
<basefont> The obsolete HTML Base Font element (<basefont>) sets a default font face, size, and color for the other elements which are descended from its parent element.
<bgsound> The Internet Explorer only HTML Background Sound element (<bgsound>) sets up a sound file to play in the background while the page is used; use <audio> instead.
<big> The obsolete HTML Big Element (<big>) renders the enclosed text at a font size one level larger than the surrounding text (medium becomes large, for example).
<blink> The HTML Blink Element (<blink>) is a non-standard element which causes the enclosed text to flash slowly.
<center> The obsolete HTML Center Element (<center>) is a block-level element that displays its block-level or inline contents centered horizontally within its containing element.
<command> The HTML Command element (<command>) represents a command which the user can invoke. Commands are often used as part of a context menu or toolbar.
<content> The HTML <content> element—an obsolete part of the Web Components suite of technologies—was used inside of Shadow DOM as an insertion point, and wasn't meant to be used in ordinary HTML.
<dir> The obsolete HTML Directory element (<dir>) is used as a container for a directory of files and/or folders, potentially with styles and icons applied by the user agent.
<element> The obsolete HTML <element> element was part of the Web Components specification; it was intended to be used to define new custom DOM elements.
<font> The HTML Font Element (<font>) defines the font size, color and face for its content.
<frame> <frame> is an HTML element which defines a particular area in which another HTML document can be displayed. A frame should be used within a <frameset>.
<frameset> The HTML <frameset> element is used to contain <frame> elements.
<image> The obsolete HTML Image element (<image>) is an obsolete remnant of an ancient version of HTML lost in the mists of time; use the standard <img> element instead.
<isindex> <isindex> is an obsolete HTML element that puts a text field in a page for querying the document.
<keygen> The HTML <keygen> element exists to facilitate generation of key material, and submission of the public key as part of an HTML form. This mechanism is designed for use with Web-based certificate management systems. It is expected that the <keygen> element will be used in an HTML form along with other information needed to construct a certificate request, and that the result of the process will be a signed certificate.
<listing> The HTML Listing Element (<listing>) renders text between the start and end tags without interpreting the HTML in between and using a monospaced font. The HTML 2 standard recommended that lines shouldn't be broken when not greater than 132 characters.
<marquee> The HTML <marquee> element is used to insert a scrolling area of text. You can control what happens when the text reaches the edges of its content area using its attributes.
<menuitem> The HTML <menuitem> element represents a command that a user is able to invoke through a popup menu. This includes context menus, as well as menus that might be attached to a menu button.
<multicol> The HTML Multi-Column Layout element (<multicol>) was an experimental element designed to allow multi-column layouts and must not be used.
<nextid> <nextid> is an obsolete HTML element that served to enable the NeXT web designing tool to generate automatic NAME labels for its anchors.
<nobr> The non-standard, obsolete HTML <nobr> element prevents the text it contains from automatically wrapping across multiple lines, potentially resulting in the user having to scroll horizontally to see the entire width of the text.
<noembed> The <noembed> element is an obsolete, non-standard way to provide alternative, or "fallback", content for browsers that do not support the <embed> element or do not support the type of embedded content an author wishes to use.
<noframes> The obsolete HTML No Frames or frame fallback element, <noframes>, provides content to be presented in browsers that don't support (or have disabled support for) the <frame> element.
<plaintext> The HTML Plaintext Element (<plaintext>) renders everything following the start tag as raw text, ignoring any following HTML.
<shadow> The HTML <shadow> element—an obsolete part of the Web Components technology suite—was intended to be used as a shadow DOM insertion point.
<spacer> <spacer> is an obsolete HTML element which allowed insertion of empty spaces on pages. It was devised by Netscape to accomplish the same effect as a single-pixel layout image, which was something web designers used to use to add white spaces to web pages without actually using an image. However, <spacer> no longer supported by any major browser and the same effects can now be achieved using simple CSS.
<strike> The HTML <strike> element (or HTML Strikethrough Element) places a strikethrough (horizontal line) over text.
<tt> The obsolete HTML Teletype Text element (<tt>) creates inline text which is presented using the user agent's default monospace font face.
<xmp> The HTML Example Element (<xmp>) renders text between the start and end tags without interpreting the HTML in between and using a monospaced font. The HTML2 specification recommended that it should be rendered wide enough to allow 80 characters per line.

Attributes

Attributes can be applied to HTML tags to change their behavior. An attribute as 2 parts:

  1. The attribute name
  2. The attribute value

Attributes are specified within the start tag as follows:

ATTR_NAME='ATTR_VAL'

The attribute name cannot have spaces and must be one word (underscore _ allowed). Attribute value should be quoted (single or double quotes -- this is optional but it is best practice to use quotes) and can include spaces.

A HTML tag can have any number of attributes (or none at all). The attribute-value pairs are seperated from each other by a white-space (one or more spaces).

<TAG_NAME ATTR_NAME1='ATTR_VAL1' ATTR_NAME2="ATTR_VAL2">

      content

</TAG_NAME>

Uses of Attributes

Attributes have 4 uses:

  1. To modify the behavior of a HTML tag: Conside the anchor <a> tag, which is used to cross reference HTML pages. The href attribute specifies the html page to navigate to when clicked.
  <a href='http://google.com'> Go to Google </a>

Go to Google

In order to open the page in a seperate tab speicy the target attribute and set it to _blank.

  <a href='http://google.com' target="_blank"> Go to Google </a>

Go to Google

Next let us look at the <img> tag. The src attribute specifies which image should be rendered within the <img> tag. For example:

  <img src='https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'>

will render the Google logo. We can also specify the height and width of the image (in pixels) by using the height and width attributes, like so:

  <img height='100' width='200' src='https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'>
  • If you want to maintain the aspect-ratio of the image specify only one of the two (height/width) attributes.

  • It is best to use CSS to speicfy these properties, more on this later.

  1. To add CSS styling to the tag: A special attribute called style can be use to specify CSS declaration for a tag. This is one of the many ways CSS can be added to a tag. This will be discussed in detail in the CSS section.

  2. To identify and group tags: An attribute called id can be used to assign an unique identifier to a tag. This identifier can be used only for one tag and a tag can have only one id. A tag can be categorized into a group by the class attribute. A tag can have more than one class. These class names are delimted by white spaces.

  <div id="testID" class='class1 class2 class3'> </div>
  1. To attach event listeners to tags:

Events are actions done by the user on a tag like clicking, mouse hover etc. An event handler is JavaScript that needs to execute when the event occurs. The following markup will pop up a message (100) when the button is cliked.

  <button onclick="alert(100)"> Click me! </button>

The event model will be discussed in more detail in the JavaScript section.

The next section lists all HTML attributes that can be used with different html tags.

Attribute Reference

Taken from MDN web docs. Please contribute if you can.

The following table lists the defined attributes of the HTML standard. A global attribute can be used with any tag, whereas most attributes have certain tags with which they are most commonly used.

Attribute Name Description
accept List of types the server accepts, typically a file type.
accept-charset List of supported charsets.
accesskey Keyboard shortcut to activate or add focus to the element.
action The URI of a program that processes the information submitted via the form.
align Specifies the horizontal alignment of the element.
allow Specifies a feature-policy for the iframe.
alt Alternative text in case an image can't be displayed.
async Executes the script asynchronously.
autocapitalize Sets whether input is automatically capitalized when entered by user
autocomplete Indicates whether controls in this form can by default have their values automatically completed by the browser.
autofocus The element should be automatically focused after the page loaded.
autoplay The audio or video should play as soon as possible.
background Specifies the URL of an image file.
bgcolor

Background color of the element.

border

The border width.

buffered Contains the time range of already buffered media.
capture From the HTML Media Capture
The definition of 'media capture' in that specification.spec, specifies a new file can be captured.
challenge A challenge string that is submitted along with the public key.
charset Declares the character encoding of the page or script.
checked Indicates whether the element should be checked on page load.
cite Contains a URI which points to the source of the quote or change.
class Often used with CSS to style elements with common properties.
code Specifies the URL of the applet's class file to be loaded and executed.
codebase This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are stored.
color

This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format.

cols Defines the number of columns in a textarea.
colspan The colspan attribute defines the number of columns a cell should span.
content A value associated with http-equiv or name depending on the context.
contenteditable Indicates whether the element's content is editable.
contextmenu Defines the ID of a ><menu> element which will serve as the element's context menu.
controls Indicates whether the browser should show playback controls to the user.
coords A set of values specifying the coordinates of the hot-spot region.
crossorigin How the element handles cross-origin requests
csp  Specifies the Content Security Policy that an embedded document must agree to enforce upon itself.
data Specifies the URL of the resource.
data-* Lets you attach custom attributes to an HTML element.
datetime Indicates the date and time associated with the element.
decoding Indicates the preferred method to decode the image.
default Indicates that the track should be enabled unless the user's preferences indicate something different.
defer Indicates that the script should be executed after the page has been parsed.
dir Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
dirname
disabled Indicates whether the user can interact with the element.
download Indicates that the hyperlink is to be used for downloading a resource.
draggable Defines whether the element can be dragged.
dropzone Indicates that the element accept the dropping of content on it.
enctype Defines the content type of the form date when the method is POST.
enterkeyhint The enterkeyhint specifies what action label (or icon) to present for the enter key on virtual keyboards. The attribute can be used with form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable attribute).
for Describes elements which belongs to this one.
form Indicates the form that is the owner of the element.
formaction Indicates the action of the element, overriding the action defined in the <form>.
formenctype If the button/input is a submit button (type="submit"), this attribute sets the encoding type to use during form submission. If this attribute is specified, it overrides the enctype attribute of the button's form owner.
formmethod If the button/input is a submit button (type="submit"), this attribute sets the submission method to use during form submission (GET, POST, etc.). If this attribute is specified, it overrides the method attribute of the button's form owner.
formnovalidate If the button/input is a submit button (type="submit"), this boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the novalidate attribute of the button's form owner.
formtarget If the button/input is a submit button (type="submit"), this attribute specifies the browsing context (for example, tab, window, or inline frame) in which to display the response that is received after submitting the form. If this attribute is specified, it overrides the target attribute of the button's form owner.
headers IDs of the <th> elements which applies to this element.
height

Specifies the height of elements listed here. For all other elements, use the CSS >height property.

hidden Prevents rendering of given element, while keeping child elements, e.g. script elements, active.
high Indicates the lower bound of the upper range.
href The URL of a linked resource.
hreflang Specifies the language of the linked resource.
http-equiv Defines a pragma directive.
icon Specifies a picture which represents the command.
id Often used with CSS to style a specific element. The value of this attribute must be unique.
importance  Indicates the relative fetch priority for the resource.
integrity

Specifies a Subresource Integrity value that allows browsers to verify what they fetch.

intrinsicsize  This attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the size specified in the attribute.
inputmode Provides a hint as to the type of data that might be entered by the user while editing the element or its contents. The attribute can be used with form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable attribute).
ismap Indicates that the image is part of a server-side image map.
itemprop
keytype Specifies the type of key generated.
kind Specifies the kind of text track.
label Specifies a user-readable title of the element.
lang Defines the language used in the element.
language Defines the script language used in the element.
loading  Indicates if the element should be loaded lazily (loading="lazy") or loaded immediately (loading="eager").
list Identifies a list of pre-defined options to suggest to the user.
loop Indicates whether the media should start playing from the start when it's finished.
low Indicates the upper bound of the lower range.
manifest Specifies the URL of the document's cache manifest.
max Indicates the maximum value allowed.
maxlength Defines the maximum number of characters allowed in the element.
minlength Defines the minimum number of characters allowed in the element.
media Specifies a hint of the media for which the linked resource was designed.
method Defines which HTTP method to use when submitting the form. Can be GET (default) or POST.
min Indicates the minimum value allowed.
multiple Indicates whether multiple values can be entered in an input of the type email or file.
muted Indicates whether the audio will be initially silenced on page load.
name Name of the element. For example used by the server to identify the fields in form submits.
novalidate This attribute indicates that the form shouldn't be validated when submitted.
open Indicates whether the details will be shown on page load.
optimum Indicates the optimal numeric value.
pattern Defines a regular expression which the element's value will be validated against.
ping The ping attribute specifies a space-separated list of URLs to be notified if a user follows the hyperlink.
placeholder Provides a hint to the user of what can be entered in the field.
poster A URL indicating a poster frame to show until the user plays or seeks.
preload Indicates whether the whole resource, parts of it or nothing should be preloaded.
radiogroup
readonly Indicates whether the element can be edited.
referrerpolicy Specifies which referrer is sent when fetching the resource.
rel Specifies the relationship of the target object to the link object.
required Indicates whether this element is required to fill out or not.
reversed Indicates whether the list should be displayed in a descending order instead of a ascending.
rows Defines the number of rows in a text area.
rowspan Defines the number of rows a table cell should span over.
sandbox Stops a document loaded in an iframe from using certain features (such as submitting forms or opening new windows).
scope Defines the cells that the header test (defined in the th element) relates to.
scoped
selected Defines a value which will be selected on page load.
shape
size Defines the width of the element (in pixels). If the element's type attribute is text or password then it's the number of characters.
sizes
slot Assigns a slot in a shadow DOM shadow tree to an element.
span
spellcheck Indicates whether spell checking is allowed for the element.
src The URL of the embeddable content.
srcdoc
srclang
srcset One or more responsive image candidates.
start Defines the first number if other than 1.
step
style Defines CSS styles which will override styles previously set.
summary
tabindex Overrides the browser's default tab order and follows the one specified instead.
target
title Text to be displayed in a tooltip when hovering over the element.
translate Specify whether an element’s attribute values and the values of its text.
type Defines the type of the element.
usemap
value Defines a default value which will be displayed in the element on page load.
width

Establishes the element's width.

wrap Indicates whether the text should be wrapped.

Boolean Attributes

Some content attributes (e.g. required, readonly, disabled) are called boolean attributes. If a boolean attribute is present, its value is true, and if it’s absent, its value is false.

HTML5 defines restrictions on the allowed values of boolean attributes: If the attribute is present, its value must either be the empty string (equivalently, the attribute may have an unassigned value), or a value that is an ASCII case-insensitive match for the attribute’s canonical name, with no leading or trailing whitespace. The following examples are valid ways to mark up a boolean attribute:

<div itemscope> This is valid HTML but invalid XML. </div>
<div itemscope=itemscope> This is also valid HTML but invalid XML. </div>
<div itemscope=""> This is valid HTML and also valid XML. </div>
<div itemscope="itemscope"> This is also valid HTML and XML, but perhaps a bit verbose. </div>

To be clear, the values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether. This restriction clears up some common misunderstandings: With checked="false" for example, the element’s checked attribute would be interpreted as true because the attribute is present.

Other Concepts

Standalone Tags

HTML tags can be nested and this the HTML document has a tree structure. The root of this tree is the <html> tag whose child nodes are <head> and <body>. The document then branches out into different tags. Most tags can have child nodes, however there are a few exceptions to this. Certain tags are standalone i.e. they cannot have child nodes. Examples of such tags are:

  • <img>
  • <hr>
  • <input>
  • <textarea>

These tags do not need the end tags (like </img>, </hr> etc.) since they cannot have content (child nodes).

Viewport

The <body> of the html page renders the window, which is the entire page. However with the advent of mobile devices the contents of the window can be panned and zoomed. The content (part of the window) that is now visible to the user is called the viewport.

Fig: 3.3.1 Window v/s Viewport

In the interest of responsive design it makes sense to make the window and the viewport the same, so we can proceed with designing for a one size canvas. This can be done by adding the following <meta> tag within the <head> of the HTML document.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style> and <script> Tags

You can add CSS declarations directly into the html file using the <style> tag. This will be discussed in detail in CSS section.

JavaScript can be added directly into the HTML document using the <script> tag.

Linking External Files

Although both CSS and JavaScript can be embedded within the HTML document it is a good practice to use external files for each. These external files can be linked into the HTML document by using the <link> and <script> tags as follows:

 <link rel="stylesheet" href="styles.css">
 <script src="myscripts.js"></script> 

Loading Sequence

The contents of the HTML file loads in the order it is writen right-to-left and top-to-bottom. This concept becomes important when styles (in CSS) and variables (in JavaScript) are redefined.

A Simple HTML Page

We will use the concepts we have learned so far to write a simple one page resume.

Output

Publish Static HTML Using Github Pages

To publish a HTML file/project on the web, Github Pages is the free option. Although it does not provide server side processing for your project, you can still host a variety of useful projects.

All you need to do is go to Settings -> Github Pages section and choose your option to publish the repository.

Pleae create a index.html as a start page for your project.

Cascading Style Sheets (CSS)

CSS provides a way to style HTML tags. CSS was developed to make html 'clean'; that is to separate styles from tags. There are 3 important concepts in CSS:

  1. Properties
  2. Values
  3. Selectors

The easiest way to add CSS to an html tag is via the style attribute.

<TAG_NAME style='prop1:val1; prop2:val2; prop3:val3'>

      content

</TAG_NAME>

CSS properties and values are written in pairs seperated by colon (:). These pairs are themselves delimitted by semi-colons(;);

The attribute value of style is known as CSS declaration.

An external CSS file (.css extension file) consists on one or more CSS Rules. A CSS rule is made up of a CSS declaration and a CSS Selector.

  CSS Rule:
  <CSS Selector> {
   <CSS Declaration> 
  }

We know what CSS declarations look like (value of a style attribute). CSS selectors determine which tags the CSS declaration must be applied to.

Box model

In order to fully understand CSS properties and values we first need to understand the CSS Box Model.

The Box Model specifies the parts of an HTML tag that can be 'styled':

  1. Content
  2. Padding
  3. Border
  4. Margin
Fig: 4.1.1. CSS Box Model

Each of these can be independently specified for each direction - top, right, bottom and left.

Value types

Distance

For any CSS property that needs to specify distance (e.g. border-width, height, witdth etc.) it is best to use the following units.

  1. px: Specifies distance in pixels
  width: 100px;
  height: 100px;
  1. %: Specifies distance as a percentage of the parent tag
  width: 50%;
  height: 50%;

(parent has width of 200px and height of 200px)

  1. vw/vh: Specifies distance as a percent of the viewpoet width/height
  width: 30vw;
  height: 20vh;

Color

Color values can be expressed in

  1. Color name: Any valid CSS color name. Full list here.

  2. Hexadecimal notation: e.g.: #ffffff, #ff0000, #00ff00, #0000ff etc.

  3. RGB format: e.g.: rgb(255,255,255), rgba(5,2,128,.3), rgb(25,155,35), rgb(5,25,255) etc.

  4. HSL format: e.g.: hsl(120deg, 3%, 1%), hsl(10deg, 60%, 61%), hsl(40deg, 50%, 17%), hsl(0deg, 30%, 1%) etc.

CSS Properties

CSS properties are a list of tag style elements that you can set and manipulate. These include setting the parameters of the box model (like border, margin, padding) and the style of the content like color, background, font-family, font-size, line-height etc.

User agent style sheet

The browser has a built-in stylesheet that it loads. This style sheet is responsible for the basic styling you see in the browser (for e.g. links are bule and button has a background and border). When stying your document please keep in mind that you are not working with a blank-slate -- you are building on top of the user-agent style sheet. This can be viewed in the CSS Inspector section of the browser's developer tools.

Property List

The following are the list of CSS properties most browsers implement [Ref.]

CSS property
background
background-attachment
background-color
background-image
background-position
background-repeat
border (border-top, border-right, border-bottom, border-left)
border-color (border-top-color, border-right-color, border-bottom-color, border-left-color)
border-style (border-top-style, border-right-style, border-bottom-style, border-left-style)
border-width (border-top-width, border-right-width, border-bottom-width, border-left-width)
clear
clip
color
cursor
display
filter
float
font
font-family
font-size
font-variant
font-weight
height
left
letter-spacing
line-height
list-style
list-style-image
list-style-position
list-style-type
margin (margin-top, margin-right, margin-bottom, margin-left)
overflow
padding (padding-top, padding-right, padding-bottom, padding-left)
page-break-after
page-break-before
position
stroke-dasharray
stroke-dashoffset
stroke-width
text-align
text-decoration
text-indent
text-transform
top
vertical-align
visibility
width
z-index

Graceful fallback in CSS

If CSS does not understand a property or value, it moves on to the next pair. A faulty property-value pair cannot make the entire CSS style sheet invalid. This behavior of CSS is know as graceful fallback.

CSS Values

Below is a list of CSS values that can be used with CSS properties[Ref.].

Special CSS values

  1. none : This value removes the property.
  2. inherit : This value links the parents CSS definition to this property.
  3. initial : Sets property to default value.
CSS property Valid values
background Can include valid values of the following:
  • background-color
  • background-image
  • background-position
  • background-size
  • background-repeat
  • background-origin
  • background-clip
  • background-attachment
background-attachment
  • scroll
  • fixed
  • local
  • initial
  • inherit
background-color Any valid CSS colorcolor.
background-image url(/path/to/image.png)
background-position
Value Description
left top
left center
left bottom
right top
right center
right bottom
center top
center center
center bottom
If you only specify one keyword, the other value will be "center"
x% y% The first value is the horizontal position and the second value is the vertical. The top left corner is 0% 0%. The right bottom corner is 100% 100%. If you only specify one value, the other value will be 50%. . Default value is: 0% 0%
xpos ypos The first value is the horizontal position and the second value is the vertical. The top left corner is 0 0. Units can be pixels (0px 0px) or any other CSS lengthlen. If you only specify one value, the other value will be 50%. You can mix % and positions
initial Sets this property to its default value.
inherit Inherits this property from its parent element.
background-repeat
  • repeat
  • repeat-x
  • repeat-y
  • no-repeat
  • initial
  • inherit
border Can include valid values of the following:
  • border-width
  • border-style (required)
  • border-color
border-color Any valid CSS colorcolor.
border-style
  • none
  • hidden
  • dotted
  • dashed
  • solid
  • double
  • groove
  • ridge
  • inset
  • outset
  • initial
  • inherit
border-width
clear
  • none
  • left
  • right
  • both
  • initial
  • inherit
clip
  • auto
  • shape rect (top, right, bottom, left)
  • initial
  • inherit
color Any valid CSS colorcolor.
cursor
  • alias
  • all-scroll
  • auto
  • cell
  • context-menu
  • col-resize
  • copy
  • crosshair
  • default
  • e-resize
  • ew-resize
  • grab
  • grabbing
  • help
  • move
  • n-resize
  • ne-resize
  • nesw-resize
  • ns-resize
  • nw-resize
  • nwse-resize
  • no-drop
  • none
  • not-allowed
  • pointer
  • progress
  • row-resize
  • s-resize
  • se-resize
  • sw-resize
  • text
  • URL
  • vertical-text
  • w-resize
  • wait
  • zoom-in
  • zoom-out
  • initial
  • inherit
display
  • inline
  • block
  • contents
  • flex
  • grid
  • inline-block
  • inline-flex
  • inline-grid
  • inline-table
  • list-item
  • run-in
  • table
  • table-caption
  • table-column-group
  • table-header-group
  • table-footer-group
  • table-row-group
  • table-cell
  • table-column
  • table-row
  • none
  • initial
  • inherit
filter

none

  • blur(px)
  • brightness(%)
  • contrast(%)
  • drop-shadow(h-offset v-offset blur spread color)
  • grayscale(%)
  • hue-rotate(deg)
  • invert(%)
  • opacity(%)
  • saturate(%)
  • sepia(%)
  • url(/path/to/image.png)

(multiple values can be combined delimitted by spaces)

float
  • none
  • left
  • right
  • initial
  • inherit
font Can include valid values of the following:
  • font-style
  • font-variant
  • font-weight
  • font-size/line-height
  • font-family
font-family
  • family-name (e.g.: Ariel, Georgia, Times New Roman etc.)
  • initial
  • inherit
font-size
font-variant
  • normal
  • small-caps
  • initial
  • inherit
font-weight
  • normal
  • bold
  • bolder
  • lighter
  • number (e.g.: 100, 200, 300 etc.)
  • initial
  • inherit
height
left
letter-spacing
line-height
list-style

Can include valid values of the following:

  • list-style-type
  • list-style-position
  • list-style-image
list-style-image
  • none
  • url(/path/to/image.png)
  • initial
  • inherit
list-style-position
  • inside
  • outside
  • initial
  • inherit
list-style-type
  • disc
  • armenian
  • circle
  • cjk-ideographic
  • decimal
  • decimal-leading-zero
  • georgian
  • hebrew
  • hiragana
  • hiragana-iroha
  • katakana
  • katakana-iroha
  • lower-alpha
  • lower-greek
  • lower-latin
  • lower-roman
  • none
  • square
  • upper-alpha
  • upper-greek
  • upper-latin
  • upper-roman
  • initial
  • inherit
margin margin-top margin-right margin-bottom margin-left
overflow
padding padding-top padding-right padding-bottom padding-left
page-break-after
  • auto
  • always
  • avoid
  • left
  • right
  • initial
  • inherit
page-break-before
  • auto
  • always
  • avoid
  • left
  • right
  • initial
  • inherit
position
  • static
  • absolute
  • fixed
  • relative
  • sticky
  • initial
  • inherit
stroke-dasharray
stroke-dashoffset - CSS lengthlen - number (e.g.: 100, 200, 300 etc.)
stroke-width number (e.g.: 1, 2, 3 etc.)
text-align
  • left
  • right
  • center
  • justify
  • initial
  • inherit
text-decoration

Can include valid values of the following:

  • text-decoration-line (required -- underline, overline, line-through)
  • text-decoration-color (CSS colorcolor.
  • text-decoration-style (solid, wavy, dotted, dashed, double)
text-indent
text-transform
  • none
  • capitalize
  • uppercase
  • lowercase
  • initial
  • inherit;
top
vertical-align
  • baseline
  • length
  • sub
  • super
  • top
  • text-top
  • middle
  • bottom
  • text-bottom
  • initial
  • inherit
visibility
  • visible
  • hidden
  • collapse
  • initial
  • inherit
width
z-index number (e.g.: 1, 2, 3 etc.)

len CSS Length

[ Ref.]

Unit Description
cm centimeters
mm millimeters
in inches (1in = 96px = 2.54cm)
px pixels (1px = 1/96th of 1in)
pt points (1pt = 1/72 of 1in)
pc picas (1pc = 12 pt)
em Relative to the font-size of the element (2em means 2 times the size of the current font)
ex Relative to the x-height of the current font (rarely used)
ch Relative to the width of the "0" (zero)
rem Relative to font-size of the root element
vw Relative to 1% of the width of the viewport
vh Relative to 1% of the height of the viewport
% Relative to the parent element

color CSS Color

  • Hexadecimal colors
  • RGB colors
  • RGBA colors
  • HSL colors
  • HSLA colors
  • Predefined/Cross-browser color names [Ref.]:
Color Name HEX Color
AliceBlue #F0F8FF
AntiqueWhite #FAEBD7
Aqua #00FFFF
Aquamarine #7FFFD4
Azure #F0FFFF
Beige #F5F5DC
Bisque #FFE4C4
Black #000000
BlanchedAlmond #FFEBCD
Blue #0000FF
BlueViolet #8A2BE2
Brown #A52A2A
BurlyWood #DEB887
CadetBlue #5F9EA0
Chartreuse #7FFF00
Chocolate #D2691E
Coral #FF7F50
CornflowerBlue #6495ED
Cornsilk #FFF8DC
Crimson #DC143C
Cyan #00FFFF
DarkBlue #00008B
DarkCyan #008B8B
DarkGoldenRod #B8860B
DarkGray #A9A9A9
DarkGrey #A9A9A9
DarkGreen #006400
DarkKhaki #BDB76B
DarkMagenta #8B008B
DarkOliveGreen #556B2F
Darkorange #FF8C00
DarkOrchid #9932CC
DarkRed #8B0000
DarkSalmon #E9967A
DarkSeaGreen #8FBC8F
DarkSlateBlue #483D8B
DarkSlateGray #2F4F4F
DarkSlateGrey #2F4F4F
DarkTurquoise #00CED1
DarkViolet #9400D3
DeepPink #FF1493
DeepSkyBlue #00BFFF
DimGray #696969
DimGrey #696969
DodgerBlue #1E90FF
FireBrick #B22222
FloralWhite #FFFAF0
ForestGreen #228B22
Fuchsia #FF00FF
Gainsboro #DCDCDC
GhostWhite #F8F8FF
Gold #FFD700
GoldenRod #DAA520
Gray #808080
Grey #808080
Green #008000
GreenYellow #ADFF2F
HoneyDew #F0FFF0
HotPink #FF69B4
IndianRed #CD5C5C
Indigo #4B0082
Ivory #FFFFF0
Khaki #F0E68C
Lavender #E6E6FA
LavenderBlush #FFF0F5
LawnGreen #7CFC00
LemonChiffon #FFFACD
LightBlue #ADD8E6
LightCoral #F08080
LightCyan #E0FFFF
LightGoldenRodYellow #FAFAD2
LightGray #D3D3D3
LightGrey #D3D3D3
LightGreen #90EE90
LightPink #FFB6C1
LightSalmon #FFA07A
LightSeaGreen #20B2AA
LightSkyBlue #87CEFA
LightSlateGray #778899
LightSlateGrey #778899
LightSteelBlue #B0C4DE
LightYellow #FFFFE0
Lime #00FF00
LimeGreen #32CD32
Linen #FAF0E6
Magenta #FF00FF
Maroon #800000
MediumAquaMarine #66CDAA
MediumBlue #0000CD
MediumOrchid #BA55D3
MediumPurple #9370D8
MediumSeaGreen #3CB371
MediumSlateBlue #7B68EE
MediumSpringGreen #00FA9A
MediumTurquoise #48D1CC
MediumVioletRed #C71585
MidnightBlue #191970
MintCream #F5FFFA
MistyRose #FFE4E1
Moccasin #FFE4B5
NavajoWhite #FFDEAD
Navy #000080
OldLace #FDF5E6
Olive #808000
OliveDrab #6B8E23
Orange #FFA500
OrangeRed #FF4500
Orchid #DA70D6
PaleGoldenRod #EEE8AA
PaleGreen #98FB98
PaleTurquoise #AFEEEE
PaleVioletRed #D87093
PapayaWhip #FFEFD5
PeachPuff #FFDAB9
Peru #CD853F
Pink #FFC0CB
Plum #DDA0DD
PowderBlue #B0E0E6
Purple #800080
Red #FF0000
RosyBrown #BC8F8F
RoyalBlue #4169E1
SaddleBrown #8B4513
Salmon #FA8072
SandyBrown #F4A460
SeaGreen #2E8B57
SeaShell #FFF5EE
Sienna #A0522D
Silver #C0C0C0
SkyBlue #87CEEB
SlateBlue #6A5ACD
SlateGray #708090
SlateGrey #708090
Snow #FFFAFA
SpringGreen #00FF7F
SteelBlue #4682B4
Tan #D2B48C
Teal #008080
Thistle #D8BFD8
Tomato #FF6347
Turquoise #40E0D0
Violet #EE82EE
Wheat #F5DEB3
White #FFFFFF
WhiteSmoke #F5F5F5
Yellow #FFFF00
YellowGreen #9ACD32

CSS Selectors

Simple CSS Selectors

  1. Tag name: Simplest of the CSS selectors is any HTML tag name. Consider the following examples:
p{
  <CSS declaration 1>
}

div{
  <CSS declaration 2>
}

<CSS declaration 1> will be applied to all <p> tags and <CSS declaration 2> will be applied to all <div> tags.

  1. Tag id: CSS declaration can be applied to a tag with a specific id by using the # prefix. For e.g.:
#first{
  <CSS declaration 1>
}

#second{
  <CSS declaration 2>
}

<CSS declaration 1> will be applied to a tag that has id='first' and <CSS declaration 2> will be applied to a tag with id='second'.

  1. Class name: a CSS declaration can be applied to a tags with a specific class by using the . prefix. Example:
.first{
  <CSS declaration 1>
}

.second{
  <CSS declaration 2>
}

<CSS declaration 1> will be applied to all tags that have a class first and <CSS declaration 2> will be applied to all tags with the class name second.

Combining Selectors

Selectors can be combined by using commas (,).

For example instead of rewriting the <CSS declaration> like this:

#first{
  <CSS declaration>
}

.second{
  <CSS declaration>
}

They can be combined like this:

#first, .second{
  <CSS declaration>
}

Selectors written without spaces refer to tags that have all applicable selectors:

For example:

div#first.second{
  <CSS declaration>
}

The <CSS selector> will be applied to the <div> tag that has [id='first'] and a class second.'

Advanced CSS Selectors

Universal selector (*):

*{
  <CSS declaration>
}

This <CSS declaration> will be applied to every tag in the HTML document.

Attribute selector ([attr='value'])

Decendent selector

When selectors are combined with a space in-between it is interpreted as decendent of elements (from left-to-right):

Example:

div #first .second{
  <CSS declaration>
}

This <CSS declaration> will be applied to a tag that has a class second, which is a decendent of a tag which has [id='first'], which in itself is a decendent of a <div> tag. Note that these tags only have to be decendent nodes and not strictly child nodes.

Child selector (>)

It is similar to the decendent selector, by now the decendent element has to be a direct decendent -- this selector looks for parent-child nodes.

Example:

#first > .second{
  <CSS declaration>
}

This <CSS declaration> will be applied to a tag that has a class second, whose parent is a tag which has [id='first'].

Sibling selector (~)

This selector is used to select all sibling (have the same parent) elements.

#first ~ .second{
  <CSS declaration>
}

This <CSS declaration> will be applied to all tags that has a class second, who have a tag which has [id='first'] as sibling.

Adjacent sibling selector (+)

This selector is used to select all sibling (have the same parent) elements.

#first + .second{
  <CSS declaration>
}

This <CSS declaration> will be applied to a single tags that has a class second, which immediately follows a tag with [id='first'].

Other Concepts

Cascading Rules

An HTML page is read top-down and hence any CSS included (whether using <link>, <style> tag or style attribute is also read in that order. If properties are redefined, then the values are cascaded, i.e the last encountered value is the one applied.

Vendor Prefixes

Certain browsers implement experimental CSS properties and they have a browser specific vendor prefix.

-webkit-transform: scale(2); // For Safari and Chrome
-ms-transform: scale(2);  // For Internet Explorer
-moz-transform: scale(2); // For Firefox

Sometimes these experimental properties get adopted into CSS and then the vendor prefix gets dropped.

transform: scale(2); // For all browsers

Combining property-value Pairs

Certain hyphenated CSS properties can be combined into one. For example:

margin-top: 10px;
margin-right: auto;
margin-bottom: 20px;
margin-left: auto;

border-width: 1px;
border-style: dotted;
border-color: red;

can be combined as:

margin: 10px auto 20px auto;

border: 1px dotted red;

Other examples include background, padding, list-style, text-decoration, font etc.

Improving the Simple Resume with CSS

Adding CSS to the HTML resume from earlier(lines 6-42), we can improve it's look-and-feel.

Output

jQuery

jQuery is known as the syntactic-sugar for JavaScript. This means you can write valid JavaScript without having to learn the full syntax of JavaScript. jQuery is a JS library and hence all jQuery written is JS, but not the other way around.

Including jQuery

The jQuery library can be included either using a content delivery network (CDN) or via downloading and linking the jQuery JS file.

Via CDN

Include the following into the <head> of your html document

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 

Via local copy

<script src="jquery-3.5.1.min.js"></script> 

The $() function

jQuery implements the dollar function. The argument to this function can be any valid CSS selector. This makes using jQuery intuitive for designers who are familiar with CSS.

$("<CSS selector>")

Other jQuery Functions

The $() function in itself is not very useful. After selecting a group of tags (using CSS selectors), we need to do something with these tags. jQuery provides a variety of functions that do something with those tags.

We now look at some examples:

fadeOut()/fadeIn()

Consider the following example

<div id='fadeEg' style='height:100px; width:100px;background:red'></div>
<button onclick='$("#fadeEg").fadeOut()'>Fade Out</button>
<button onclick='$("#fadeEg").fadeIn()'>Fade In</button>

The <div id='fadeEg'> can be hidden or shown when the button is clicked. The onclick event triggers the jQuery written as the attribute value.

The duration of fadeIn/fadeOut (in milli-seconds) can also be specified as the argument for these functions. e.g.:

<div id='fadeEg1' style='height:100px; width:100px;background:red'></div>
<button onclick='$("#fadeEg1").fadeOut(1000)'>Fade Out</button>
<button onclick='$("#fadeEg1").fadeIn(2500)'>Fade In</button>

css()

<div id='cssEg' style='height:100px; width:100px;background:red'></div>
<button onclick='$("#cssEg").css("border", "10px solid")'>Add Border</button>
<button onclick='$("#cssEg").css("border", "")'>Remove Border</button>
<div id='cssEg1' style='height:100px; width:100px;background:red'></div>
<button onclick='$("#cssEg1").css({"border": "10px solid","background":"green"})'>Add style</button>
<button onclick='$("#cssEg1").css({"border": "","background":"red"})'>Remove style </button>

animate()

<div id='aniEg1' style='height:100px; width:100px;background:red'></div>
<button onclick='$("#aniEg1").animate({"margin-left":"70%","height":"10px"},2000)'>Add style</button>
<button onclick='$("#aniEg1").animate({"margin-left":"","height":"100px"}, 4000)'>Remove style </button>

Following is the list of some basic jQuery functions. Try them out. A full list can be found here: https://api.jquery.com/.

Function Description
hide() Hide the selected tags
show() Show the selected tags
toggle() Toggle the selected tags
slideUp() Slide up tag
slideDown() Slide down tag
slideToggle() Toggle silde up/down status of tag
hasClass() Check if selected tag has a class
addClass() Add class to selected tag
removeClass() Remove class from selected tag
toggleClass() Add/remove class
height() Height of tag
width() Width of tag

Chaining jQuery functions

jQuery functions can be chain linked like so:

$("body").addClass("night").delay(500).removeClass("night");

While chaining functions delay() (adds delay to the queue of transitions/animations) and stop() (which empties the transition/animation queue) are very useful.

Single Page Resume, with jQuery

Improving on where we left off we add night mode to our resume. We add the following new CSS (lines 44-56):

body.dark{
  font-family: courier;
  background: black;
  color: white;
}
body.dark a{
  color: white;
}
body.dark h2,
body.dark tr{
  background: white;
  color: black;
}

and makeup for 2 buttons (lines 61,62):

<button onclick='$("body").removeClass("dark")'>Regular</button>
<button onclick='$("body").addClass("dark")'>Dark Mode</button>

In order to enable night mode by default we attach an onload event listerner to <body> (line 60):

<body onload='$("body").addClass("dark")'>

Full HTML

Output

JavaScript (JS)

JavaScript is an Object-Oriented programming language that preserves C-like syntax. As the name implies it is a scripting language and is hence interpreted (as opposed to compiled). A JS Interpreter is a program that reads valid JS and executes it one statement at a time (line-by-line).

JS Intepreters can be stand alone or can be packaged within other programs like browsers and database shells. This interpreter can be accessed via the console. In a browser this console can be accessed via Developer Tools.

Fig: 6.1 Browser Js console (Google Chrome)
Fig: 6.2 Node.js Console

All JS within the HTML page is interpreted on this console. The console understands all valid JS. To try out the console type any arithmetic expression (say 1+3) and the console should return the write answer back.

In the next few sections we will learn about JS syntax, data types, objects, functions and other concepts.

JS Syntax

A JS program is a list of JS statements. Each statement is interpreted on the console one at a time. Each statement is delimited from another by either a semicolon (;) or a newline.

A Javascript program is read top-to-bottom, left-to-right. This is known as the execution sequence. Programming involves manipulating the execution sequence in order to achieve specific computational tasks.

Statements

JS statements are made up of:

  1. Keywords: Keywords are special words that provide commands to the interpreter. Keywords cannot be overloaded (i.e. used as variable names).

The following is the list of JS keywords (an incomplete list; new keywords are added to JS on a regular basis):

break, case, catch, continue, debugger, default,
delete, do, else, finally, for, function, if,
in, instanceof, new, return, switch, this, throw, 
try, typeof, var, void, while, with

This is not a complete list as JS continues to evolve and new keywords can be added.

  1. Values: Values can either be fixed or variable. Fixed values are called literals and variable values are called variables.

Example of literals include constants like 1, 100, 3.142 etc.

Variables are subject to the variable lifecycle that includes (in that order) -- declaration, definition and usage.

A variable is declared in a JS statement by using the var keyword. For e.g.:

var x;

Multiple variables can also be declared in one statement:

var x,y,z;

These statements serve the purpose of "declaring" these variables to the interpreter. JS does not require a declaration statement, but it is best practice to use these declarative statements, to ensure readability and ease of debugging.

The next stage in the lifecycle of a variable is definition. A variable is defined using the assignment (=) operator. For example:

x = 10;
y = "test string"

Once a variable is defined (it is undefined by default) it can be used as a placeholder for value. e.g.:

z = x + y;
  1. Operators: Operators are special characters (similar to mathematical operators) that specify a particular operation to the interpreter. The following is the list of basic operators:
Operator Description
= Assignment
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
Table: 6.1.1 Binary Operators
Operators can be classified (based on the number of operands) as:
  • Unary Operators: These operators take in one operand as input. Some examples are:
Operator Description
++ Increment
-- Decrement
Table: 6.1.2 Unary Operators
  • Binary Operators: Binary operators require 2 operands. All standard examples mentioned before (Table 6.1.1) are binary operators. The following as some special binary assignment operators:
Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y
Table: 6.1.3 Binary Assignment Operators
  • Ternary Operators: JavaScript supports one ternary operator -- ?:. It can be combined with an assignment operator to assign different values. For example:
var fee = (age > 18) ? '$12.00' : '$2.00'

The variable fee will be assigned to '$12.00' if age > 18 and will be assigned a value of '$2.00' otherwise.

  1. Expressions: JS expressions are statements that combine operators and operands (literals and variables). We have seen examples of this before. Here are more:
x = 6 + 8 + z;
y = a++ * 10;
  1. Comments: JavaScript supports both single-line and multi-line comments. Single line comments begin with a // and are delimited by the end of line. Multiple line comments start with /* and end with */.
// This is a single line comment

/*
This is 
a multi-line
comment
*/

Variable Names

JS variable does not have to be single characters like x, y, z etc. But can be anything as long as the following rules are followed:

  1. The variable name can contain numbers, alphabets (alpha-numeric), underscore(_) and dollar sign ($).
  2. The first character of a variable has to be an alphabet, underscore(_) or dollar sign($).
  3. Variables canot be a JS reserved keyword.
  • Variable names are case sensitive. Therefore age, Age and AGE are 3 distinct variables.
  • Variable names cannot start with numbers.
  • Variable names cannot contain spaces. Use camel-case or underscores to ensure readability of multiple word variable names (e.g.: maxValue or max_value).
  • There is no length limit on JS variable names (a good rule-of-thumb is to limit it to 32 characters).

JS Data Types

JavaScript variables are loosely typed, that is the data type of a variable can be changed at anytime. This is an important distinction from other strongly typed languages such as C, C++ and Java.

var Keyword

Since JS is loosely typed there is only one variable declaration type -- using the var keyword (as opposed to a language like C, which has int, float, char and other variable types).

typeof Operator

Even though there is only one type of variable declaration, JS does have different data types. Loose typing allows for the same variable (think of it as a container for values) to be reassigned to different data types. The typeof operator allows us to inspect the datatype of the variable.

var x;
typeof x; // undefined

x = 1;
typeof x; // number

x = "a string";
typeof x; // string

Undefined

A variable that is yet to be assigned a value is of the type Undefined. It holds the value undefined.

Note that the Undefined data type has only one value undefined.

Numbers

When a varible is assigned a number (whether a whole number of a decimal it is now holds the data type Number.

Apart from regular whole numbers and decimals there are some special Number values. For example:
var x = 9/0; // Infinity
typeof x; // number

x = -x // - Infinity
typeof x; // number

x = 0/0 // NaN -- not a number
typeof x; // number

Number Methods

Number is not an object (objects will be discussed in detail later), but a variable with typeof "number" has some methods associated with it.

toString()

A number can be converted to its string representation by the toString() method.

var x = 10;
y = x.toString();
typeof y; // string

x = 3.142;
y = x.toString();
typeof y; // string

This method also allows for conversion from one base to another.

var x = 13;
y = x.toString(2); // 1101
z = x.toString(16); // d

toFixed()

This function allows convertion to different precision strings

var x = 13;
y = x.toFixed(2); // 13.00
z = x.toFixed(1); // 13.0

toExponential()

This function converts numbers into its scientific notation string.

var x = 13;
y = x.toExponential(2); // 1.30e+1
z = x.toExponential(1); // 1.3e+1
a = x.toExponential(0); // 1e+1
Other Number mainipulation Methods

parseInt()

This function converts strings to respective integers.

parseInt("13"); // 13
parseInt("3.142"); // 3
parseInt("3slndv"); // 3
parseInt("3.14slndv"); // 3

parseFloat()

parseFloat("13"); // 13
parseFloat("3.142"); // 3.142
parseFloat("3slndv"); // 3
parseFloat("3.14slndv"); // 3.14

String

String is a built in data-type in all JS interpreters. A String can be assigned to any variable by the assignment (=) operator. A string literal can be enclosed with either single or double quotes.

var st = "a string"; // string assignment
var st1 = 'another string'; // string literals can use either single or
double quotes

Each element (character) of the string can be indexed by using its index, or the position. Remember strings are zero-indexed i.e. indexing starts with zero. Therfore st[0] refers to the first character in a string, st[1] refers to the second character and so on. The total number of characters can be accessed by the length property.

var st = "a string"; 
var len = st.length; // 8

A string is also an object and has built-in methods. Let is look at a few of them in action.

var st = "a string";
var x = st.indexOf("s"); // 2

var words = st.split(" "); // [ "a", "string" ]

var aChar = st.charAt(6); // "n"

var charCode = st.charCodeAt(6); // 110 

A full list of String methods are listed below.

String Methods

[ Ref.]

Method Description
charAt() Returns the character at the specified index (position)
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a new joined strings
endsWith() Checks whether a string ends with specified string/characters
fromCharCode() Converts Unicode values to characters
includes() Checks whether a string contains the specified string/characters
indexOf() Returns the position of the first found occurrence of a specified value in a string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a string
localeCompare() Compares two strings in the current locale
match() Searches a string for a match against a regular expression, and returns the matches
repeat() Returns a new string with a specified number of copies of an existing string
replace() Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced
search() Searches a string for a specified value, or regular expression, and returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
startsWith() Checks whether a string begins with specified characters
substr() Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale
toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object

Arrays

Arrays are another built in data-type that allows the programmer to manage lists. Unlike strings, which only allows characters to be part of the list, arrays can have any valid JS value(variable/literal) as members. Similar to string, the number of list members can be accessed via the length property.

var arr = ["a", 1, "a string", 3.14];
var len = arr.length; // 4

Array Methods

[ Ref.]

Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
copyWithin() Copies array elements within the array, to and from specified positions
entries() Returns a key/value pair Array Iteration Object
every() Checks if every element in an array pass a test
fill() Fill the elements in an array with a static value
filter() Creates a new array with every element in an array that pass a test
find() Returns the value of the first element in an array that pass a test
findIndex() Returns the index of the first element in an array that pass a test
forEach() Calls a function for each array element
from() Creates an array from an object
includes() Check if an array contains the specified element
indexOf() Search the array for an element and returns its position
isArray() Checks whether an object is an array
join() Joins all elements of an array into a string
keys() Returns a Array Iteration Object, containing the keys of the original array
lastIndexOf() Search the array for an element, starting at the end, and returns its position
map() Creates a new array with the result of calling a function for each array element
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new length
reduce() Reduce the values of an array to a single value (going left-to-right)
reduceRight() Reduce the values of an array to a single value (going right-to-left)
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
slice() Selects a part of an array, and returns the new array
some() Checks if any of the elements in an array pass a test
sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result
unshift() Adds new elements to the beginning of an array, and returns the new length
valueOf() Returns the primitive value of an array

Boolean

The Boolean data type contains 2 values true and false;

var x = true;
typeof x // boolean

x = false;
typeof x // boolean

Before continuing with more complex data-types (objects) and functions we will now look at more operators and programming constructs used in JavaScript.

More on Operators

The JavaScript execution sequence is one statement at-a-time, left-to-right (like we would read English). However operators and certain programming constructs(if/else, for, while etc.) can alter this. We now look at how operators affect the execution sequence.

Operator Precedence

Consider the assignment operator:

var x = 2 + 3;

The assignment operator has 2 operands, commonly known as the left-hand-side (var x) and the right-hand-side (2 + 3). The default execution sequence dicatates that the left-hand-side be evaluated by the interpreter first. The assignment operator changes this. It dictates that the right-hand-side is evaluated first. Thus the expression 2 + 3 is evaluated (5) and then is assigned to the left-hand-side. That is, the variable declaration and assignment happens after the right-hand-side expression is evaluated.

All other operators also alter the execution sequence. The interpreter uses the precedence order to evaluate operators. The following table lists the precedence of each JS operator.

Precedence Operator type Associativity Individual operators
21 Grouping n/a ( … )
20 Member Access left-to-right … . …
Computed Member Access left-to-right … [ … ]
new (with argument list) n/a new … ( … )
Function Call left-to-right … ( )
Optional chaining left-to-right ?.
19 new (without argument list) right-to-left new …
18 Postfix Increment n/a … ++
Postfix Decrement … --
17 Logical NOT right-to-left ! …
Bitwise NOT ~ …
Unary Plus + …
Unary Negation - …
Prefix Increment ++ …
Prefix Decrement -- …
typeof typeof …
void void …
delete delete …
await await …
16 Exponentiation right-to-left … ** …
15 Multiplication left-to-right … * …
Division … / …
Remainder … % …
14 Addition left-to-right … + …
Subtraction … - …
13 Bitwise Left Shift left-to-right … << …
Bitwise Right Shift … >> …
Bitwise Unsigned Right Shift … >>> …
12 Less Than left-to-right … < …
Less Than Or Equal … <= …
Greater Than … > …
Greater Than Or Equal … >= …
in … in …
instanceof … instanceof …
11 Equality left-to-right … == …
Inequality … != …
Strict Equality … === …
Strict Inequality … !== …
10 Bitwise AND left-to-right … & …
9 Bitwise XOR left-to-right … ^ …
8 Bitwise OR left-to-right … | …
7 Logical AND left-to-right … && …
6 Logical OR left-to-right … || …
5 Nullish coalescing operator left-to-right … ?? …
4 Conditional right-to-left … ? … : …
3 Assignment right-to-left … = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
… &&= …
… ||= …
… ??= …
2 yield right-to-left yield …
yield* yield* …
1 Comma / Sequence left-to-right … , …

Operator Polymorphism

The same operator can perform different operations depending on the operands provided to it. This is known as operator polymorphism.

This concept is best explained using the addition(+) operator.

Look at the following examples:

var num = 10;
var st = "hello";

typeof num; // "number"
typeof st; // "string"

var x = num + 20; // 30
typeof x; // "number"

var y = st + "world"; // "hello world"
typeof y; // "string"

var z = num + st; "10hello"
typeof z; // "string"

z = st + num; "hello10"
typeof z; // "string"

Comparison Operators

These are binary operators that compare if the operands are equal to, greater than, less than etc.

Operator Description Examples returning true
Equal (==) Returns true if the operands are equal. 3 == var1

"3" == var1

3 == '3'
Not equal (!=) Returns true if the operands are not equal. var1 != 4
var2 != "3"
Strict equal (===) Returns true if the operands are equal and of the same type. 3 === var1
Strict not equal (!==) Returns true if the operands are of the same type but not equal, or are of different type. var1 !== "3"
3 !== '3'
Greater than (>) Returns true if the left operand is greater than the right operand. var2 > var1
"12" > 2
Greater than or equal (>=) Returns true if the left operand is greater than or equal to the right operand. var2 >= var1
var1 >= 3
Less than (<) Returns true if the left operand is less than the right operand. var1 < var2
"2" < 12
Less than or equal (<=) Returns true if the left operand is less than or equal to the right operand. var1 <= var2
var2 <= 5

Logical Operators

These operators can be used to combine 2 comparison operators. The operands are Boolean (or else they are typecast to Boolean).

Operator Description Example var x = 9, y = 2;
&& and (x < 10 && y > 1) is true
|| or (x == 5 || y == 5) is false
! not !(x == y) is true

Decisions and Looping

Code Blocks

A code block is a group of JS statements that are enclosed in between curly braces ({}). Certain code-blocks allow for modification of the execution sequence in interesting ways -- decision making and iteration.

if(){}/else(){}

The if/else construct lends itself to implementing binary decision trees in JS. An if/else block has the following syntax:

if( <CONDITION> ){
  // execute statements in block
  // if the <CONDITION> is true
}
else{
  // execute statements in block
  // if the <CONDITION> is false
}

The <CONDITION> can be any valid JS expression. Unlike other languages the <CONDITION> does not have to strictly evaluate to a Boolean true or false. The Interpreter will typecast the <CONDITION> to the nearest Boolean value (Either true or false).

Consider the following example where different entry prices apply depending on age.

var entryPrice, moviePrice;
if(age < 3){
  entryPrice = 0;
  moviePrice = 0;
}
else if(age < 16){
  entryPrice = 10;
  moviePrice = 2;
}
else{
  entryPrice = 100;
  moviePrice = 20;
}

switch(){}/case

This construct allows implementation of decision trees and is best suited for more than 2 decison options. Consider the following example of assigning grades:

// score variable holds the percent score earned by student
var grade;
if(score < 60){
  grade = "D";
}
else if(score < 70){
  grade = "C";
}
else if(score < 90){
  grade = "B";
}
else{
  grade = "A";
}

This can also be implemented using switch/case:

switch (score){
  case (score < 60):
    grade = "D";
    break;
  case (score < 70):
    grade = "C";
    break;
  case (score < 90):
    grade = "B";
    break;
  default:
    grade = "A";
    break;
}

The break keyword

The break keyword exits the code block. It is necessary in switch/case as without a break the execution continues into the next set of statements.

while(){} and for(){}

The two constructs allow for iteration. This will be explained by iterating over an array to find the minimum and maximum value from a list of values.

Consider the following list of values:

var values = [3, 13, 14, 234, 12, 4, 13, 54, 64, 76, 65];

This list can be iterated using an index variable i and the while() loop as follows:

var i = 0; // define an initialize the index variable
// JS arrays are zero-indexed

while(i < values.length){
  console.log(values[i]);
  i++; //equivalent to i = i + 1;
}

This same while loop can be written as a for loop as follows:

for(var i = 0; i < values.length; i++){
  console.log(values[i]);
}

As you can observe the for loop combines the index initialization and increment together with the conditional.

while and for are equivalent -- anything you can do with while yiou can do with for and vice-versa.

Now let us look how we can find the minimum and maximum value of an array using while and for.

// Using while
var values = [3, 13, 14, 234, 12, 4, 13, 54, 64, 76, 65];
var min = Infinity;
var max = 0;
var i = 0;
while(i < values.length){
  if(values[i]>max){
    max = values[i];
  }
  if(values[i]<min){
    min = values[i];
  }
  i++;
}
// Using for
var values = [3, 13, 14, 234, 12, 4, 13, 54, 64, 76, 65];
var min = Infinity;
var max = 0;
for(var i = 0; i < values.length; i++){
  if(values[i]>max){
    max = values[i];
  }
  if(values[i]<min){
    min = values[i];
  }
}

The continue keyword

The continue keyword gets the control (execution sequence) to the end of the code block.

Let us look at an example on how to use this. In this example we will calculate the average of a list of values that are positive.

var values = [-1, -5, 35, 43, 234, -67, 76, 64, 34, 77];
var sum = 0;
for (var i = 0; i < values.length; i++){
  if(values[i] < 0){
    continue;
  }
  sum = sum + values[i];
}
var avg = sum/values.length;

Functions

Function in JS allow you to reuse code (easy to copy bits) again-and-again with differemt inputs(known as arguments). Depending on the input the function does computation (processing of statements) and returns an output (known as return value).

Fig: 6.6.1 function() Block Diagram

Syntactically the function is a code block (a list of statements) that treat input arguments as local variables. It returns an empty value (when no return statement is found, or there is an empty return statement) or any JS variable. The return value can be assigned to any JS variable.

var function = <FUNCTION_NAME>(<ARGUMENTS>){
  /*
    Valid JS statements
    to execute
  */

  return; // return undefinied
}

Sementically the function is just another variable, hence function names have the same naming restrictions as variables.

Let is consider the following example in which a function converts temperature from Celcius to Farenheit.

var c2f = function(c)
{
  var f = c * 1.8 + 32;
  return f;
}

This function returns the Farenheit value of input temperature in Celcius. It can be invoked as follows:

var c = 100;
var f;
f = c2f(c); // 212
f = c2f(56.4); // 133.51999999999998
f = c2f(80.45); // 176.81

In order to preserve C like syntax JS allows for the following function declaration syntax as well:

function <FUNCTION_NAME>( <ARGUMENTS> ){
  /*
    Valid JS statements
    to execute
  */

  return; // return undefinied
}

Built in Functions

alert()

This function takes in a String argument (other variables are typecast to String) and displays it as a pop-up message for the user. Try these in your browsers JS console:

alert(1);
alert("hello world")

confirm()

This function is used to get true/false feedback from user. The argument String is shown as a prompt.

var response = confirm("Yes or No?");
alert(response);

prompt()

This function is used to get single line input feedback from user. The argument String is shown as a prompt.

var response = prompt("Enter your name:");
alert(response);

console.log()

This function is used to print debug information into the console. On the browser this can be accessed via Developer Tools. It prints to console any string given as argument (other data types are typecast).

Objects

Objects are a built in data type. An Object is a collection of properties(variables) and methods(functions), which are called members of the Object.

We have already looked at 2 built in objects -- Strings and Arrays. They both have property length and many different methods.

Object property and methods can be accessed via the dot (.) operator or through box brackets ([]). For example the string property length can be accessed as follows:

var s = "a test string";
var len = s.length; // using dot operator
var len = s["length"]; // using box brackets

Similarly any methods (say indexOf()) can be accessed similarly:

var s = "a test string";
var pos = s.indexOf(a); // using dot operator
var pos = s["indexOf"](a); // using box brackets

Object Syntax

var obj = { property_1:   value_1,   // property_# may be an identifier...
            2:            value_2,   // or a number...
            // ...,
            'property n': value_n }; // or a string

Built In Objects

In this section we look at more built in objects.

The Object Object

There is a built-in Object called Object. This has one useful static method that we will discuss here. Object.keys() returns the list of all the objects member keys. It is very handy when you want to iterate the Object.

var keys = Object.keys(location) // can be used to get keys on any object

for(var i = 0; i < keys.length; i++){
  console.log("Key: " +keys[i]);
  console.log("Key value: " + location[keys[i]]);
}

The Date Object

The Date object provides an easy way to store and manipulate dates in JS.

Each Date object stores a particular date and time. Initializing a Date object without arguments will give you the current date-time.

var now = new Date();

The new keyword

The new keyword is used to create a new object. Notice that we did not use new() to create Arrays and Strings. That is because they are built-in objects which can be instantiated without new(although you could if you choose to).

As an object Date() has built in methods[Ref]:

Method Description
Date()

Gets today's date and time

getDate()

Gets the day of the month for the specified date according to local time.

getDay()

Gets the day of the week for the specified date according to local time.

getFullYear()

Gets the year of the specified date according to local time.

getHours()

Gets the hour in the specified date according to local time.

getMilliseconds()

Gets the milliseconds in the specified date according to local time.

getMinutes()

Gets the minutes in the specified date according to local time.

getMonth()

Gets the month in the specified date according to local time.

getSeconds()

Gets the seconds in the specified date according to local time.

getTime()

Gets the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.

getTimezoneOffset()

Gets the time-zone offset in minutes for the current locale.

getUTCDate()

Gets the day (date) of the month in the specified date according to universal time.

getUTCDay()

Gets the day of the week in the specified date according to universal time.

getUTCFullYear()

Gets the year in the specified date according to universal time.

getUTCHours()

Gets the hours in the specified date according to universal time.

getUTCMilliseconds()

Gets the milliseconds in the specified date according to universal time.

getUTCMinutes()

Gets the minutes in the specified date according to universal time.

getUTCMonth()

Gets the month in the specified date according to universal time.

getUTCSeconds()

Gets the seconds in the specified date according to universal time.

getYear()

Deprecated - Gets the year in the specified date according to local time. Use getFullYear instead.

setDate()

Sets the day of the month for a specified date according to local time.

setFullYear()

Sets the full year for a specified date according to local time.

setHours()

Sets the hours for a specified date according to local time.

setMilliseconds()

Sets the milliseconds for a specified date according to local time.

setMinutes()

Sets the minutes for a specified date according to local time.

setMonth()

Sets the month for a specified date according to local time.

setSeconds()

Sets the seconds for a specified date according to local time.

setTime()

Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.

setUTCDate()

Sets the day of the month for a specified date according to universal time.

setUTCFullYear()

Sets the full year for a specified date according to universal time.

setUTCHours()

Sets the hour for a specified date according to universal time.

setUTCMilliseconds()

Sets the milliseconds for a specified date according to universal time.

setUTCMinutes()

Sets the minutes for a specified date according to universal time.

setUTCMonth()

Sets the month for a specified date according to universal time.

setUTCSeconds()

Sets the seconds for a specified date according to universal time.

setYear()

Deprecated - Sets the year for a specified date according to local time. Use setFullYear instead.

toDateString()

Gets the "date" portion of the Date as a human-readable string.

toGMTString()

Deprecated - Converts a date to a string, using the Internet GMT conventions. Use toUTCString instead.

toLocaleDateString()

Gets the "date" portion of the Date as a string, using the current locale's conventions.

toLocaleFormat()

Converts a date to a string, using a format string.

toLocaleString()

Converts a date to a string, using the current locale's conventions.

toLocaleTimeString()

Gets the "time" portion of the Date as a string, using the current locale's conventions.

toSource()

Gets a string representing the source for an equivalent Date object; you can use this value to create a new object.

toString()

Gets a string representing the specified Date object.

toTimeString()

Gets the "time" portion of the Date as a human-readable string.

toUTCString()

Converts a date to a string, using the universal time convention.

valueOf()

Gets the primitive value of a Date object.

In Addition there are 2 static Date() methods[Ref]:

Method Description
Date.parse()

Parses a string representation of a date and time and returns the internal millisecond representation of that date.

Date.UTC()

Gets the millisecond representation of the specified UTC date and time.

window Object (browser only)

For browser based JS, the window is the topmost object. All other objects and variables are derived from the window object.

Fig: 6.5.1 window Object

Therefore when we write console.log() it is interpreted as window.console.log().

The window object encapsulates other important objects such as -- location (which has useful members such as location.href, location.hash, location.host, location.reload() etc.) and document.

document Object (browser only)

Document Object Model (DOM)

The Document Object Model (DOM) is the represenation of the HTML document within JS. The DOM has an object associated with each element (tag) within the HTML document. The corresponding object can be used to read tag information (query status of attributes and their values) as well as set tag attribute values. Thus a DOM provides a way to read attribute values from tags (including CSS declarations, since style is an attribute) and set them.

The document Object has important DOM access methods such as document.getElementById(), document.getElementsByTagName() , document.getElementsByClassName() etc

What about jQuery?

jQuery is a wrapper that implements different functions on top of JS. The main dollar function ($()) in jQuery internally uses the DOM (document Object, more specifically the document.querySelectorAll() function).

Slideshow Library

In this section we will discuss how to implement an library for creating embeddable sildeshows using HTML/CSS and JS.

Demo

Code Repo

Usage

In order to create an embeddable slideshow, create <iframe> with source as lib.html with hash as a list of comma-seperated URLs to images.

Example:

  <iframe src='lib.html#https://upload.wikimedia.org/wikipedia/commons/1/1a/VIC0725Stevenson1944_%28cropped%29.jpg,https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/D%C3%A1il_Chamber.jpg/320px-D%C3%A1il_Chamber.jpg,https://upload.wikimedia.org/wikipedia/commons/thumb/0/04/Sinustrombus_sinuatus%2C_Bohol%2C_Philippines.jpg/320px-Sinustrombus_sinuatus%2C_Bohol%2C_Philippines.jpg'> </iframe>

To run this example locally:

  1. $ git clone https://github.com/tejaswigowda/PtC-slideShowLibrary.git
  2. $ cd PtC-slideShowLibrary
  3. $ http-server -p 9005
  4. Open http://127.0.0.1:9005 in browser.

Implementation

The library is implemented in lib.html and the demonstration is in index.html. Let us take a look at lib.html first:

The static markup for this example is straight-forward (lines 76-87). It included <div id="imgWrapper"> that will be populated by the slides and <div id="numWrapper"> that will hold the numbers of the slides. There are also navigation buttons -- Next (line 85) and Previous (line 80).

  <body>
  <div id='imgWrapper'>
  </div>

  <button id='prev' onclick='goPrev()'> </button>

  <div id='numWrapper'>
  </div>

  <button id='next' onclick='goNext()'> </button>

    </body>

The CSS (lines 9-75 styles the slideshow. It makes sure that the slides are placed one behind another (hidden, except the current slide); the numbers indicating the number of slides is at the bottom, and the previous and next arrows are to the left and right of the screen respectively. Note that jQuery is also included via CDN (line 5).

The JS is triggered after the page loads (since it is after the <body> tag) and first gets the list of images to be used in the slide show (line 89).

var imgs = location.hash.replace("#","").split(",")

By iterating over the imgs variable the markup for the numbers at the bottom are created at attached(lines 90-94).

var markup = "";
for(var i = 0; i < imgs.length; i++){
    markup = markup + "<button onclick='goToSlide(" + i + ")'>" + (i+1) + "</button>"
}
document.getElementById("numWrapper").innerHTML = markup;

Another iteration over the array of image URLs(imgs) creates the markup for the slide show itself (lines 96-100).

var markup = "";
for(var i = 0; i < imgs.length; i++){
  markup = markup + "<div style='background-image:url(" + imgs[i] + ")'></div>"
}
document.getElementById("imgWrapper").innerHTML = markup;

The variable currSlide keeps track of the index of the current slide (zero-indexed) (defined in line 102).

var currSlide = 0;

The function triggered by the user (by clicking the numbers on the bottom is goToSlide(). This is defined in lines 104-112.

var goToSlide = function(n){
  $("#imgWrapper div").css("opacity", 0);
  $($("#imgWrapper div")[n]).css("opacity", 1);


  currSlide = n;
  $("#numWrapper button").removeClass("active")
  $($("#numWrapper button")[currSlide]).addClass("active")
}

This function is also invoked by the goPrev() (invoked when user clicks Previous button) and goNext() (invoked when user clicks Next button). These functions are defined in lines 115-129.

var goPrev = function(){
  currSlide = currSlide - 1;
  if(currSlide < 0){
    currSlide = imgs.length - 1;
  }
  goToSlide(currSlide);
}

var goNext = function(){
  currSlide = currSlide + 1;
  if(currSlide > imgs.length - 1){
    currSlide = 0;
  }
  goToSlide(currSlide);
}

On line 114, goToSlide(0) is called to initialize the slide show to the first slide.

Advanced Topics

In this section we will disuss:

  1. JSON
  2. Sorting JS arrays (with sorting basics)
  3. Image processing via HTML Canvas
  4. CSS Transitions and Transforms
  5. CSS Animations
  6. Responsive Design

Please complete the section of JS Objects before continuing.

JSON

JavaScript Object Notation (JSON) is exactly what the name implies -- it is representing data as JS Objects. Therefore JSON syntax is identical to the object syntax.

// JSON Syntax
{
    property_1:   value_1,   // property_# may be an identifier...
    2:            value_2,   // or a number...
    // ...,
    'property n': value_n   // or a string
}; 

In practice JSON is a file that holds the string that defines the JS Object.

To make it easy to work with JSON, JS Intepretors have a build in JSON Object. It has two important static methods -- JSON.parse() and JSON.stringify() that allow to parse a JSON String into an Object and vice-versa respectively.

var obj = {
  name: "Jane Doe",
  classes:[ "Programming the Web", "Database Management", "Operating Systems"],
  school: "ABC Academy" 
}

var jsonString = JSON.stringify(obj); 
  // '{"name":"Jane Doe","classes":["Programming the Web","Database Management","Operating Systems"],"school":"ABC Academy"}'

var objCopy = JSON.parse(jsonString); 

JSON is strictly a data-interchange format, and can hold any data-type with the exception of functions.

Sorting

With JSON data and JS arrays, dorting based on a particular key becomes an useful operation. In this section we discuss the basics of sorting by looking at bubbule sort as a standard sorting algorithm.

Bubble Sort

Bubble Sort is a sorting algorithm that sorts the array two members at a time. The idea of bubble sort is simple -- look at two adjacent elements in the array; are they sorted?. If already sorted then do nothing; if unsorted swap the position of the 2 elements.

Fig: 7.2.1 Sorting Logic

How many passes (iterations) of the array is needed? -- no more than the size of the array. Let us look at sorting an array [6,5,3,1,8,7,2,4]

var arr = [6,5,3,1,8,7,2,4];
for (var i = 0; i < arr.length; i++){
  for (var j = 0; j < arr.length -i; j++){
    if(arr[j]>arr[j+1]){
      var temp = arr[j];
      arr[j] = arr[j+1];
      arr[j+1] = temp;
    }
  }
}

console.log(arr);

This process is visualized below [Ref.]:

Other Sorting Algorithms

Bubble Sort is just one of the many different sorting algorithms. The similarity between all these is that they all employ the sorting operator. They differ in only how they traverse and iterate over arrays. Therefore the key to any sorting is the comparison operator.

Sorting JS Arrays

JS array has a built in sort() method. An array can be sorted like so:

var arr = [6,5,3,1,8,7,2,4];
arr.sort();

The above invocation of sort() uses the default sorting function function(a,b){ return a > b }, and is equivalent to:

arr.sort(function(a,b){ return a > b });

To sort the array in decending order we reverse the sorting function.

arr.sort(function(a,b){ return a < b });

Since the built-in sort() method of Arrays, allows us to customize the sorting operator we can now sort Arrays of object based on any key.

var arr = [
{fname:"John",
 lname:"Smith"},
{fname:"Jane",
 lname:"Dow"},
{fname:"Alice",
 lname:"Hernandez"},
{fname:"Bob",
 lname:"Patel"},
{fname:"Rob",
 lname:"Grande"},
{fname:"Sally",
 lname:"Mendez"}
];

// sort by first name (alphabetical order)
arr.sort(function(a,b){return a.fname > b.fname});

// sort by first name (reverse alphabetical order)
arr.sort(function(a,b){return a.fname < b.fname});

HTML Canvas

CSS Transtions

Demo

CSS Transforms

Demo

Front End Web Technologies

Front End Web Technologies

Front End Web Technologies

Full Stack Programming

Full Stack Programming

Full Stack Programming

Full Stack Programming

Full Stack Programming

What is IoT?

Internet of Things (IoT) is an emerging field that focusses on connecting everyday objects to the Internet. What does it mean to connect everyday objects to the Internet? It means to implement clients and servers on low-power, low-cost, small computers (known as microcontrollers) to control everyday objects. This section will teach you the basics of programming clients/servers on ESP32, a production ready IoT platform.

Why IoT?

IoT has the following commercial and consumer applications [Ref.]:

  • Consumer applications
    • Smart home
    • Elder care
  • Organisational applications
    • Medical and healthcare
  • Transportation
    • Vehicle communications
    • Building and home automation
  • Industrial applications
    • Manufacturing
    • Agriculture
    • Infrastructure applications
  • Metropolitan scale deployments
    • Energy management
    • Environmental monitoring

Future of IoT

The commercial and industrial applications of IoT are now well understood and different solutions are being developed. IoT device adaption is expected to rise over the next couple of decades [Ref.].

Fig: 10.1 IoT device adoption

Development Environment

ESP32 is a low-power system-on-chip (SoC) that integrates Bluetooth and Wifi capabilities on a single board. It is made by Espressif and has been deployed in working IoT products. It is a good choice to learn to program to learn basic IoT concepts.

ESP32

The ESP32 chip has the following features:

  • Processors:
    • CPU: Xtensa dual-core (or single-core) 32-bit LX6 microprocessor, operating at 160 or 240 MHz and performing at up to 600 DMIPS
    • Ultra low power (ULP) co-processor
  • Memory: 520 KiB SRAM
  • Wireless connectivity:
    • Wi-Fi: 802.11 b/g/n
    • Bluetooth: v4.2 BR/EDR and BLE (shares the radio with Wi-Fi)
  • Peripheral interfaces:
    • 12-bit SAR ADC up to 18 channels
    • 2 × 8-bit DACs
    • 10 × touch sensors (capacitive sensing GPIOs)
    • 4 × SPI
    • 2 × I²S interfaces
    • 2 × I²C interfaces
    • 3 × UART
    • SD/SDIO/CE-ATA/MMC/eMMC host controller
    • SDIO/SPI slave controller
    • Ethernet MAC interface with dedicated DMA and IEEE 1588 Precision Time Protocol support
    • CAN bus 2.0
    • Infrared remote controller (TX/RX, up to 8 channels)
    • Motor PWM
    • LED PWM (up to 16 channels)
    • Hall effect sensor
    • Ultra low power analog pre-amplifier
  • Security:
    • IEEE 802.11 standard security features all supported, including WFA, WPA/WPA2 and WAPI
    • Secure boot
    • Flash encryption
    • 1024-bit OTP, up to 768-bit for customers
    • Cryptographic hardware acceleration: AES, SHA-2, RSA, elliptic curve cryptography (ECC), random number generator (RNG)
  • Power management:
    • Internal low-dropout regulator
    • Individual power domain for RTC
    • 5μA deep sleep current
    • Wake up from GPIO interrupt, timer, ADC measurements, capacitive touch sensor interrupt
Fig: 11.1 ESP 32 pinout

T Watch

T Watch is a wearable development module that integrates ESP32 along with many sensors. It has a USB-C interface using which it can be charged and programmed. It has 2 free GPIOs that can be used to hook up additional sensors.

Fig: 11.2 T Watch

Arduino IDE

Even though we are not programming Arduino chips, we can use their Integrated Development Environment (IDE) to program ESP32 chips. The Arduino IDE includes:

  1. Code Editor
  2. Code Compilier
  3. Binary Loader

Arduino C++

The code in this section will be written in Arduino C++. Since this book has introduced JS, it should be easy to transition into Arduino C++, since both languages have borrowed syntax from C.

Please take a look at the Arduino C++ language reference for details. The code will be explained when first introduced.

T-Watch

The TTGO T Watch comnines ESP32 and other sensors onto a single board.

Fig: 12.1 T Watch Pinout
Fig: 12.1 T Watch

Let us now write our first program, compile it and run it on the T Watch.

Hello World

  1. Download and install Arduino:

https://www.arduino.cc/en/Main/Software

  1. Add this to your boards (in Arduino-->Preferences):
https://dl.espressif.com/dl/package_esp32_dev_index.json

more instructions: https://github.com/espressif/arduino-esp32/blob/master/docs/arduino-ide/boards_manager.md

  1. Install USB to UART Driver: https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers
  2. Install T-Watch library https://github.com/Xinyuan-LilyGO/TTGO_TWatch_Library (Clone this git repository into your Arduino/libraries folder).
  3. Clone https://github.com/tejaswigowda/PtC-tWatchHelloWorld.git
git clone https://github.com/tejaswigowda/PtC-tWatchHelloWorld.git
  1. Open helloWorld.ino in Arduino IDE.
  1. Connect watch via USB cable and choose your port in Arduino IDE.

  2. Compile and run!

Touch Pad

The T Watch has a reliable input output using the touchpad module. We have seen how to print to the touch screen in the Hello World example. In this section we will get user input (touches) and display output using the touch pad.

Serial Input/Output

For debugging purposes the Serial Port will be very useful. We have already used the serial port to write to the T-watch's program memory (when we loaded compiled binary of helloWorld.ino). In this section we will learn to programmatically read and write to the Serial Port.

Built in User Button

Pulse Width Modulation (PWM)

Digital Write

PWM Emulation using digitalWrite()

ESP32 PWM

Wifi

HTTP Server

Asynchronous web client

HTTP Client

Sensor Kit

The sensor kit has modules that can be plugged into the T Watch. The sensor kit comes with the following modules:

  • Button module: a switch that can control the passage or open circuit.
  • Pir infrared sensor module: commonly used for security alarms and automatic lighting applications. Pir sensor detects movement, but does not provide information about the motor or moving object.
  • Door contact sensor module: it is a device for security alarm. It consists of a wireless transmitter and a permanent magnet. It is used to detect whether doors, windows, drawers, etc. are illegally opened or moved.
  • RGB module ws2812: can send multiple colors by mixing the red, green and blue color.
  • Microphone module: is a device or transducer that converts sound into an electrical signal.
  • Dht11 module: it is a sensor combined with temperature and humidity detection components. The built-in processor converts the measured temperature and humidity data into digital signals and then sends the data.
  • Dual-function extension module: the expansion module can be freely combined with several modules.

Fig: 11.1 T Watch

Programming the Internet of Things (IoT)

Bibliography