Simple Static Web Apps

Learning to make web apps starts simply, in the browser. Let’s get started making our very first web apps.

Static Web Apps

A static web app is a web app that in which all of the HTML, CSS, and JavaScript are completely written ahead of time, never generated by a server.

A First Example

We will start very simply.

The HTML

Starting with CodeSandbox or any other development environment (The p5js Web Editor, Replit, Glitch, etc.), build your index.html like so (you might have extra items in the head, depending on how your editor primes your workspace, it’s all good):

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>Distance Converter</h1>
    <p>
      <input id="in"> in =
      <span id="cm">?</span> cm
    </p>
    <script src="sketch.js"></script>
  </body>
</html>

An HTML file only states what elements should appear in your document. The head contains information about the document; the body contains what you see—in this case a level-one heading (h1) and a paragraph (p) containing a text input box (input), some text, and a span element. Elements are built from tags. There is almost always a start tag and usually an end tag. An element can also have attributes, which must appear in the start tag, and content, which appears between the tags. The HTML file does not define how the elements look nor how they behave. HTML is pure structure. The link and script elements connect your document to the CSS and JavaScript files that define the look and behavior: create empty files for these if your development environment did not already create them.

The elements of the document form a tree:

trivialhtmltree.png

The tree that structures the elements is called the DOM. DOM is short for Document Object Model. That’s because what browsers show you is a document, and the document is made up of objects (well, elements really, but the name “object” stuck), and the HTML provides a structure, or model, or how the objects fit together.

Interested in Computer Science?

If so, you should get used to trees. They are ubiquitous in all areas of computer science.

The CSS

HTML defines only the structure of an app; CSS defines its presentation, sometimes called the look-and-feel. What do we mean by presentation? Lots of things:

Our code-along will only show simple styles for now; we will end up with this:

style.css
body {
  margin: 0;
  padding: 0;
  background-color: skyblue;
}
h1 {
  background-color: blue;
  color: white;
  margin-top: 0;
  padding: 20px;
  font-family: cursive;
}
p {
  margin-left: 20px;
}

This stylesheet has three rulesets. A ruleset has a selector and property-value pairs.

The JavaScript

We’ve see that HTML is for structure and CSS is for presentation. JavaScript is for behavior. JavaScript is a popular, powerful programming language that can be used pretty much anywhere. It’s superpower is that it was designed to facilitate the construction of asynchronous, interactive, event-driven software. For example, in a web browser, programs mainly just look like this:

When event X occurs, perform action Y.

In our simple distance-converter app, we want to say:

When anything is input in our text box, update the span with the new computed value.

Here’s the JavaScript code we will build and explain in the code-along:

const inputBox = document.querySelector('#in')
const answerSpan = document.querySelector('#cm')

inputBox.addEventListener('input', report)

function report() {
  const inches = inputBox.value
  const centimeters = inches * 2.54
  if (isNaN(centimeters)) {
    answerSpan.textContent = '?'
  } else {
    answerSpan.textContent = centimeters
  }
}
File names

The actual file names for the CSS and JS files don’t matter too much. Many development environments pre-create these files and give them names like the ones we used here, namely style.css and sketch.js. Feel free to rename them and give them more meaningful names, perhaps bmi.css and bmi.js.

Worth restating:

Exercise: Reacll the three main parts of a web app and what each is responsible for. Don’t simply memorize, but make sure to put images in your head of how exactly each of the responsibilities is carried out.

A Slightly More Complex App

Our next code-along will be a little fancier. We’ll have two input boxes. 😮

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>BMI Calculator</title>
    <link rel="stylesheet" href="bmi.css">
    <script src="bmi.js" defer></script>
  <head>
  <body>
    <h1>BMI Calculator</h1>
    <p>Weight in pounds <input id="weight"></p>
    <p>Height in inches <input id="height"></p>
    <p>The BMI is <span id="answer"></span></p>
  </body>
</html>
Exercise: Study the relationship between the written HTML and the picture below. See if you can reconstruct the drawing from the HTML code (without peeking, of course).

simplehtmltree.png

The JavaScript program has three main parts:

  1. Get HTML elements into JavaScript variables by calling document.querySelector with a selector expression.
  2. Attach event listeners to certain elements, so that when an event happens on an element, a particular function is called.
  3. Implement the functions to handle the events, generally by updating properties on elements (which will automatically make the browser update its display).
bmi.js
const KILOGRAMS_PER_POUND = 0.453592
const METERS_PER_INCH = 0.0254

const heightBox = document.querySelector('#height')
const weightBox = document.querySelector('#weight')
const answerSpan = document.querySelector('#answer')

heightBox.addEventListener('input', updateBMI)
weightBox.addEventListener('input', updateBMI)

function updateBMI() {
  const pounds = Number(weightBox.value)
  const inches = Number(heightBox.value)
  const kilograms = pounds * KILOGRAMS_PER_POUND
  const meters = inches * METERS_PER_INCH
  const bmi = kilograms / (meters * meters)
  answerSpan.textContent = bmi.toFixed(2)
}

This code along is great opportunity to learn about some technical aspects of JavaScript and programming!

CLASSWORK
In groups of 2-4, extend this BMI application with some enhanced styling (try a background image, some borders, better colors, different fonts, and so on). In the HTML file, try type="number" as an attribute for both of the input elements. See if you can line up the text entry boxes (we haven’t covered this in class, so ask around or search the web, surely CSS has something that might help).
Exercise: Recall the three main sections of the JavaScript program.

More HTML Elements

Lists

Tables

Progress Bar

input types

Selectors

So, you’ve built a beautiful, complex DOM for your web app. You have hundreds of elements, beautifully nested in a way that perfectly describes your content in a meaningful way.

Now you need to identify elements, or specific groups of elements, so that you can style them (with CSS) or interact with them (with JavaScript). There are lots and lots of ways to make selectors. In the examples above we saw these selectors:

Here’s a list of some other kinds of selectors:

ExampleDescription
......

Here is a more complete list.

Wait, How about learning selectors the fun way? Play CSS Diner.

Exercise: Seriously, play CSS Diner. Complete every level!

Fancier Styling

It seems fitting to take a sneak peak at some of the things you can do with CSS before moving on.

Colors, Shadows, Alignment, and Transforms

Our next code-along will show a message on a rainbow background with some crazy font decorations and rotation. Think of this as a base for exploring CSS, not as a recommended way to style up text in a “real” webapp.

body {
  background-color: #cccccc;
  margin: 0
}
section {
  margin: 10px;
  border: 8px dashed linen;
  font: bold italic 50px Avenir, Helvetica;
  color: white;
  text-shadow: 1px 1px 2px black;
  text-align: center;
  background-image: linear-gradient(90deg, red, yellow, orange, green, blue, purple);
  padding: 30px;
  transform: rotate(-5deg);
}

CLASSWORK
Speaking of being creative, go ahead and experiment with styles and text. There are several places on the web with tutorials and references for CSS; More complete coverage of CSS will come later in the course.
Styling and Accessibility

Be careful with styling. There are a number of things you need to be aware of, such as not using color to carry meaning (some users may have degrees of color-blindness) and don’t use pictures for text (as some visually-impaired users may require screen readers). Styling can be overdone and detract from your message. However, styling can enhance usability and the user experience, so by all means learn and practice how to style well.

Grid Layout

When you first learn CSS, you start with colors, fonts, borders, padding, margins, shadows, and simple text alignment (left, center, right). Maybe you do transforms (translate, scale, rotate) early.

But a huge part of CSS is known as layout. CSS offers two layout schemes: grid and flex. Grid gives you the ability to section up your page like so:

How exactly does it work? There are a zillion options. Here are some tutorials:

Exercise: Play CSS Grid Garden.

One of the main uses for grid is to layout a site with a header, footer, navigation panel, and main content area. Sometimes you will want your app to take up the entire browser viewport and anchor the header and footer to the top and bottom of the viewport, and allow the content inside to scroll.

Flex Layout

While grid is generally used for big-picture layout, Flex (aka “Flexbox”) is more about laying out a bunch of items in a row, or maybe in a column, and maybe they “wrap”. To get started, you’ll want to understand three things:

We’ll study them in class using this little widget that you can explore with:

Of course there is a great deal more to flex! Check out:

Exercise: Play Flexbox Froggy.
Exercise: Play Flexbox Defense.

Transitions

CSS properties can be transitioned from one value to another over time. The simplest example is probably to start the transition on hover:

<body><p>Hello</p></body>
p {
  text-align: center;
  transition: transform 3s;
}
p:hover {
  transform: scale(5);
}

There are four parts to a transition:

You normally write them all together with the transition property. Example:

transition: width 2.5s ease 0.5s
CLASSWORK
We will practice with more transitions, for now, all using hover.

Transitions, like all other CSS properties, can be affected with JavaScript. In the JavaScript section below, there is an example of starting transitions with various events.

Here are some good tutorials and guides for transitions:

Fancier JavaScript

In a web app, JavaScript gives you interactivity:

So far we’ve only seen getting (1) listening for text box actions via the input event, (2) reading the content of a text box with .value and (3) updating the content of a span element with .textContent. Let’s do more!

CLASSWORK
Code-Along Time! We'll make an app that progresses like so:
  1. Draw a ball where the mouse is clicked.
  2. Transition the ball to move, in an animated fashion, to where the mouse is clicked
  3. Have the ball follow the mouse, with the mousemove event.

Along the way we will learn about string interpolation and perhaps other cool JavaScript features.

Exercise: Events for you to research: mouseover, mouseout, mousedown, mouseup, focus.

Bringing It All Together

It’s crucial to remember:

HTML

The content, or structure. The DOM. Elements and Attributes.

CSS

The presentation, or look-and-feel. Rules and Properties.

JavaScript

The behavior, or interaction. Can dynamically change the DOM and the styles.

Here are the essential elements, CSS properties, and JavaScript events we’ve covered so far. How many do you recall?

HTMLCSSJavaScript
ELEMENTS:
  • html
  • head
  • meta
  • title
  • link
  • script
  • body
  • h1
  • p
  • input
  • span
  • header
  • footer
  • section
  • div
PROPERTIES:
  • margin
  • padding
  • border
  • color
  • background-color
  • background-image
  • font-family
  • font
  • text-align
  • text-shadow
  • display
  • transform
FUNCTIONS:
  • querySelector
  • addEventListener

PROPERTIES:
  • textContent
  • style
  • value

EVENTS:
  • click
  • input
  • mousemove
Events are one of JavaScript’s signature capabilities

JavaScript is known for being all about events. The set of events a JavaScript program can listen for and respond to is set by the environment (browser, mobile device, server, etc.) and programmers can create their own events, too. Here are some events you may encounter:

  • input, when the text inside an element changes (by typing, cutting, pasting, etc.)
  • keydown, when a key has been pressed down
  • mouseenter, when the mouse cursor has been moved into the bounding box of the element
  • open, when a web socket connection has been established
  • touchend, when a touchpoint has been removed from a touch surface
There are hundreds more.

Learning More

These notes have just barely introduced you to HTML, CSS, and JavaScript, covering far less than 1% of what is out there. You’re just getting started. Where can you learn more?

HTML Resources

CSS Resources

JavaScript Resources

Summary

We’ve covered:

  • The relationship between HTML, CSS, and JavaScript
  • What The DOM is
  • A few HTML elements and attributes
  • Some very basic CSS
  • JavaScript in the Browser
  • Where to learn more