Skip to content

Latest commit

 

History

History
534 lines (383 loc) · 18.8 KB

2.md

File metadata and controls

534 lines (383 loc) · 18.8 KB

The Front End

Let's get more familiar with HTML, CSS, and JavaScript.

Introduction to HTML

What is HTML?

Hyper-Text Markup Language, or HTML, is considered a markup language rather than a programming language because it is logic-less. It describes a document rather than instructing the computer to perform operations.

Most programming languages are very strict. A single wrong space, misplaced semicolon, or unclosed parenthesis can break the entire programme. By contrast, HTML is a forgiving language. Almost no HTML document is 100% compliant with the official HTML standard. This works because the standard defines how browsers should interpret invalid HTML, and most of the time the browser's result matches the author's intent.

Elements and Tags

Content, like text or images or videos, is structured into HTML elements. The HTML standard defines a set of elements that represent different content types. Elements mark-up content by surrounding it in tags. Most elements have an opening and closing tag. Tags are wrapped in angle brackets. The closing tag contains a forward slach (/).

<p>This is a paragraph element containing some text.</p>

Some elements are self-closing because they do not contain content. They omit the closing tag. Here we see the horizontal rule (hr) and line break (br) self-closing tags.

<hr>
<br>

Reference of HTML 5 Elements

Attributes

Opening and self-closing tags may contain one or more named attributes. The available attributes depend on the specific HTML element.

All attributes have a name. Most have a value that must be wrapped in quotes if it contains spaces.

<img src="photo.jpg" alt="My favourite photo">

Some attributes have no specific value, only a name. Their presence, or lack thereof, acts as a boolean value.

<button disabled>You can't click me!</button>
<input type="checkbox" checked>

Nested Elements

Elements with start and end tags can contain other elements. While HTML is a forgiving language, you will end up with difficult to understand HTML code if care is not taken to close nested elements in the correct order that they were opened.

<p>
  <b>This is bold</b>, and <u>this is underlined</u>.
</p>
<p> <b>But <u>what</b> about</p> this?</u> ... oh dear!

Tip: Repeated whitespace (i.e. spaces, tabs, and line breaks) is collapsed by the browser into a single space. Self-discipline is key to writing tidy, maintainable code.

Protip: Lazy (read: efficient) programmers use tools called linters to detect potential mistakes and assist with code formatting.

Named Characters

Because some characters have a special meaning, like angle brackets, a problem arises when the document contains them as content. Imagine writing a document about HTML: How will the browser know which tags are part of the HTML markup and which are merely example code snippets?

The solution is to escape these special characters using ampersand notation.

  • &lt; for < (less-than)
  • &gt; for > (greater-than)
  • &amp; for & (ampersand)

This way we can include example code in actual tags.

<p>The &lt;p&gt; tag is for text.</p>

Output:

The <p> tag is for text.

Comments

Comments are a special pair of tags tells the browser to skip any content contained within.

<!-- This is a comment. The browser does not display it. -->

Document

The HTML standard has been around for decades. Over time changes continue to be made, resulting in several versions of HTML. HTML documents first declare a doctype to indicate which version of HTML is being used. For HTML 5, the current standard, it is simply:

<!doctype html>

A document then begins with its root element. There can be only one root element and it is always the html element.

<html>
</html>

The document continues with two structural elements: the head element and the body element. The head contains meta information about the document, while the body contains the actual content that is displayed on screen.

<!doctype html>
<html>
  <head>
    <title>My little web page</title>
  </head>
  <body>
    <p>
      Here's my picture:
      <img src="me.png" alt="That's me!">
    </p>
  </body>
</html>

Beauty!

Recommended Reading

The lifecycle of a web request

Simplified model

Browsers perform a sequence of steps when loading a web page.

  1. Download the URL specified by the address bar from a web server.
  2. Parse the web page's HTML source code into a Document Object Model (DOM) tree structure.
  3. Download any referenced files like images, scripts, stylesheets, videos, etc.
  4. Start executing the JavaScript source code, if any.
  5. Render the page on screen based.

In overwhelming detail

Browser de-bugging

Debugging is the process of figuring out what the computer is doing, typically when the result is not as intended.

Keep Calm

When bugs are hard to solve, it's important to remember: It's always logical. There is always a reason. Computers are honest.

Break down the process into steps to confirm expected outcomes at each step. Diligently eliminate possibilities until the root cause is revealed.

Browser Tools

Different browsers have different debugging tools. Let's take a look at the Google Chrome DevTools.

https://developer.chrome.com/devtools

HTML & CSS debugging

Right-click any element in a web page, choose Inspect Element. The DevTools reveal the selected element in the DOM and display its applied CSS rules.

Tip: Changes made here are not saved to your HTML and CSS source files. To reset any changes made, simply refresh the page.

JavaScript debugging

Open the DevTools and choose the console tab. This provides an interactive prompt, called a REPL (Read–eval–print loop), for simple experimenting with JavaScript code.

Tip: Any code entered here runs in the context of the active browser tab. Use DOM methods to manipuate the page.

Network debugging

Go to the Network tab in the DevTools to see what happens when the browser downloads the page and its referenced content. This will help track down the cause of slow load times.

HTML5/CSS3

The HTML and CSS specifications are managed by the World Wide Web Consortium (W3C).

The HTML 5 specification defines many aspects browsers should adhere to: HTML elements, URL formats, source code parsing, DOM methods, and much more.

There are many other features in modern browsers that exist as independent specifications. It's common to talk about these standards under the banner of HTML 5 but technically they are not part of the HTML 5 specification.

CSS is split into many modules covering things like layout, fonts, values & units, backgrounds & borders, media queries, selectors, colors, and so on. Each module has its own version, with most currently said to be at level 3. Some modules, like selectors and borders & backgrounds, have proposals for level 4.

Caveat Emptor

Since standards are continuously evolving, support in browsers varies. To discover new specifications and find out their real-world support look at the CanIUse statistics.

Introduction to CSS

What is CSS?

By default HTML elements look very plain. CSS is a language to tell to the browser's renderer how to display DOM elements.

It is a separate language from HTML and does not add semantics to the document.

Syntax

CSS files are called stylesheets. A stylesheet is a set of rules. Each rule has a selector and a declaration of properties with values.

h1 {
  font-size: 36pt;
}
p {
  font-size: 12pt;
}
img {
  width: 160px;
  height: 90px;
}

The syntax of CSS is quite forgiving. If the browser does not understand a line of CSS source code it simply skips that line. This is a doube-edged sword however as it can be frustrating to track down a bug when a certain CSS rule is simply not being applied.

Selectors

So far we used only simple element name selectors. More complex designs call for precise targeting of elements. CSS provides a powerful selectors syntax.

Let's look at some examples:

/* all "h1" elements */
h1 {}

/* all "em" elements inside a "p" element */
p em {}

/* the element with "id" attribute "story" */
#story {}

/* all elements with "class" attribute containing "urgent" */
.urgent {}

See more: http://www.w3.org/TR/css3-selectors/#selectors

Cascading, Inheritance, & Specificity

When CSS rules target the same element with different values for the same property, the browser needs to work out which rule wins out by calculating the specificity of each selector. Factors that matter to specificity include the order in the stylesheet, the use of ID and CLASS selectors, selector nesting, and more.

* { color: blue; }
em { color: orange; }
p { color: red; }
p { color: orchid; }
p::first-letter { color: green; }
<p><em>Hello</em> world</p>

Result: http://codepen.io/cbas/pen/yYyepL

Properties & Values

Once we have selected our desired elements, their visual properties can be overridden using custom values.

For a list of available properties and details on their supported values, see: https://developer.mozilla.org/en-US/docs/Web/CSS/Reference

Tip: Use the Inspect Element technique explained above to learn how web pages achieve effects.

Text

Set the typeface to a built-in font style:

font-family: serif;
font-family: sans-serif;
font-family: cursive;
font-family: monospace;

Load a custom font using snippets from Google Web Fonts.

@import url(https://fonts.googleapis.com/css?family=Lobster);
h1 { font-family: 'Lobster', cursive; }

Set text-decoration to underline or line-through, or remove default decorations with none.

Set text to italic with font-style: italic;.

Make text bold with font-weight: bold;.

Color

CSS supports several models to specify colours. Hexadecimal Red-Green-Blue (e.g. #ff0000 or #f00 or rgb(255, 0, 0)), named colours (e.g. pink or gold, and transparent), or Hue-Saturation-Lightness (hsl(0, 100%, 50%)).

A fourth channel, called alpha, is used to specify opacity. For example #f008 or rgba(255, 0, 0, 128).

Layout

The display and various box model properties are used to control the size and palcement of elements.

Display

Most commonly set to either block, inline, or inline-block. This roughly means whether or not the element starts on a new line.

Box Model

Browsers compute the location of elements by calculating their size and then stacking them in order, space permitting.

These properties control much of this behaviour:

width
height
padding
border
margin

External Stylesheet

Add an external stylesheet to our HTML document by using the link element.

<link rel='stylesheet' href='homepage.css'>

Using a separate CSS file makes it easier to manage a growing source code base. The same CSS file can also be re-used across HTML documents.

Further Reading

Overview of Javascript fundamentals

What is JavaScript?

JavaScript is a powerful language supported by all web browsers. We use it to implement rich, interactive behaviour. This turns static HTML documents into full-fledged web applications.

ECMAScript

It is formally known as ECMAScript. It is currently at version 6, though most browsers only fully support version 5, with growing support for new language features.

Note: JavaScript is not related to Java other than by their similar names. They are very different languages.

Java is to JavaScript as pain is to painting. https://twitter.com/_ericelliott/status/574658222763565056

But wait, there's more!

As a general purpose programming language, JavaScript is also used outside of the web browser. For back-end development with the Node.js environment, building extensions for applications like Google Apps Script, or even running on hardware microcontrollers like Espruino and Tessel.

Additionally it has become a target for transpilation of other programming languages like C++, Python, Ruby, and others to allow those programmes to run in the web browser.

Variables

To keep track of data in our programme, we assign names to things. These are called variables because the data represented by a name may change.

Variables are declared with the var, let, and const keywords. Values of variables declared as let or var can be changed. Variables declared as const, called constants, never change their value. The difference between let and var lies in the scoping of variables, which means they are not accessible from the entire programme, only specific areas considered "within the scope".

Programming languages deal with different types of data. JavaScript offers several built-in types, called primitives. The most commonly used types are strings, numbers, booleans, arrays, objects, and functions.

var name = 'Alice' // variable "name" contains the string "Alice"
let score = 1337 // variable "score" contains the number 1337
const happy = true // constant "happy" has the boolean value true (as opposed to false)

var colours = ['red', 'orange', 'yellow'] // variable colours is an array of strings

var classroom = { name: 'PFNP' } // variable classroom is an object
                                 // with the "name" property
                                 // set to a string of value "PFNP"

Tip: Properties of objects can be accessed using the . syntax. For example:

classroom.name

Operators

JavaScript can perform operations on variables like assignment, multiplication/division, addition/subtraction, string concatenation, equality checking, and more.

See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators

var hours_elapsed = 5;
var seconds_in_hour = 60 * 60;
var seconds_elapsed = hours_elapsed * seconds_in_hour;
// 18000

var first_name = 'Alice';
var title = 'Ms.';
var welcome = 'Hello, ' + title + ' ' + first_name;
// "Hello, Ms. Alice"

var fruit1 = 'apple';
var fruit2 = 'pear';
fruit1 === fruit2
// false

Functions

Units of logic that perform a specific task are grouped as a function. This allows them to be re-used easily or passed around as data (in JavaScript functions are objects and can be treated as variables).

// defining a function that sums two numbers
function sum (a, b) {
  return a + b
}

// calling the function returns the computed value
sum(2, 5)
// 7

var age = 20
sum(age, 10)
// 30

Methods

Objects can have properties that are functions. The built-in types also have some handy methods.

var name = 'Alice'
console.log(name.toUpperCase())
// ALICE

var sequence = [1, 2, 3, 4, 5]
console.log(sequence.reverse())
// [5, 4, 3, 2, 1]

window.alert("Have a nice day :)")
// a popup dialog appears

var dog = {
  bark: function () {
    console.log('Woof! Woof!')
  }
}
dog.bark()
// Woof! Woof!

Iteration

Loop over arrays to perform an operation on every value.

var friends = ['Bob', 'Carol', 'Dan', 'Eve']
friends.forEach(function (name) {
  console.log('Hello, dear ' + name)
})

Branching

By using the if/else pattern the flow of the programme is controlled.

if (age >= 18) {
  drink('tiger')
} else {
  drink('milo')
}

JavaScript in the browser

The HTML document is parsed by the browser into the Document Object Model (DOM). The DOM is exposed to JavaScript code, allowing it to be modified dynamically.

Globals

All JavaScript code in the browser has access to the window global variable, which contains references to everything the browser has to offer. Some of its properties, like document, location, and navigator, are also available as global variables.

Working with the DOM

document.querySelectorAll('h1')
// list of all "h1" element nodes in the current document

document.querySelector('p').innerText = 'Hello world!'
// changes the content of the first paragraph

Events

document.querySelector('button').addEventListener('click', function (event) {
  console.log('Clicked the button!')
})

Learning Resources

How to get help with frameworks

Online:

  • RTFM: Choose a framework with proper documentation.
  • Google is your friend. Someone probably blogged about it.
  • Stack Overflow probably has some copy & paste-able solution.

Singapore:

JQuery & Bootstrap

My recommendation: Avoid these old frameworks. Code for standards. Polyfills help fill the gaps in browser support without getting trapped in ageing libraries and frameworks.

Exercise: creating a full working web page

This repository contains an example front-end stack in the src directory.

Developer Tools

Install these applications:

  • io.js

    Runs JavaScript on your command line. This is the latest version of Node.js.

  • GitHub Desktop

    Source code management. Use it to clone this repository and publish your code.

  • Atom

    Text editor for source code. Use it to edit HTML, CSS, and JS files.

Cloning

  1. Go to the cbas/pfnp repository and fork it to make a copy of this code in your GitHub account.
  2. Use GitHub Desktop to clone your forked repository onto your local machine.

Editing

Open in Atom from the GitHub Desktop application.

Installation

  1. Open a command line window and use the cd command to navigate to the cloned repository.

Tip: In GitHub Desktop, right-click the pfnp repository and choose Open in Terminal (OS X) or Open in Command Prompt (Windows).

  1. Download all dependencies for the app.

npm install

Tip: This may also require native platform development tools. Install Xcode (OS X) or Visual Studio Express (Windows) if necessary.

Running

Perform automated code checks and tests:

npm test

Launch the production server:

npm start

Run the developer toolchain:

npm run dev

Developing

Open the repository folder in Atom and edit the HTML/CSS/JS files in ./src.