2b: HTML, CSS, JS

Plus a Git refresher

Objective

Understand the basics of web core technologies - HTML, CSS and JS - and how these work together to render websites in browsers.

This is a quick grounding on a core technology area, and something unfortunately is expected to be a prerequisite for this module.

We will quickly go over some basics (and hopefully you have some exposure), and then dive deeper into JS later.

Introduction

  • HTML (HyperText Markup Language) is the language that provides the structure for websites.
  • CSS (Cascading Stylesheets) is a language specification that helps define the presentation of a markup language like HTML.
  • Finally, JS (Javascript) is the high-level language that enables interactivity for websites.

HTML

A very, very simple basic HTML template.


<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Hello World</title>
</head>
<body>
  <h1>Hello World!</h1>
</body>
</html>
                    

Hopefully you have seen this before.

HTML 2

A quick selection of tags you should know:

  • Paragraphs: <p>
  • Headings: <h1> to <h6>
  • Ordered and unordered lists: <ul>, <ol> and <li>
  • Links: <a href="...">
  • Images: <img src="...">
  • Divs and spans: <div> and <span>

Other useful ones: iframe, table, form, etc.

Resource: W3schools

Resource: HTML.com

CSS

Sample CSS code snippet:


/* these are classes */
.term-grid {
  max-width: 1000px;
  margin: auto;
  color: #222;
  border-bottom: 1px solid #ddd;
  padding: 1em 0;
}

.term-grid label:first-child {
  text-align: right;
}

/* this is an id */
#helloWorld {
  color: #fff;
}
                    

Hopefully this is familiar!

CSS 2

Some basic things that CSS can specify:

  • Colors, backgrounds, borders
  • Basic box model: margins, paddings, height, width, overflow
  • Images, media, forms styling
  • Fonts styling
  • Transformations - translations, rotations, etc.
  • Interface properties: visibility, hidden, hover, etc.
  • Layout: flexbox, grid

Resource: W3schools

CSS 3

Things you should know:

  • Specifying selectors: By class, id, attribute, etc. (here's a list)
  • Cascade, specificity and inheritance. Basically a later rule overwrites earlier ones, and a tag can inherit various rules (more details)
  • Data types, especially specifying units. Most common: px, em (more details)
  • Debugging: code inspector (use Chrome)

CSS 4

Responsitivity: Because you want the code to work across multiple form factors.

Sample media query CSS code on div class:


/* If the screen size is 601px or more, set font-size to 80px */
@media (min-width: 601px) {
  div.example {
    font-size: 80px;
  }
}

/* If the screen size is 600px or less, set font-size to 30px */
@media (max-width: 600px) {
  div.example {
    font-size: 30px;
  }
}
                    

Other useful responsive tags: grid, flexbox

CSS frameworks

Nowadays it is very common to use a CSS framework to define for us all the nice UI elements without having to code a lick of CSS.

Let's try this out with the very popular Bootstrap CSS framework.

Javascript

JS is everywhere. Originally used for website client-side page behavior, its popularity has led to it being used on backend tech stacks / frameworks like node.js.

JS is a multi-paradigm mix and match of functional, object-oriented and procedural language.

Comprehensive Resource: javascript.info

JS 2

Things you should know:

  • Conditionals, loops, variables, functions
  • Objects, arrays
  • Basic debugging. Console.log is your friend!

DOM

  • The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web.
  • The backbone of HTML is tags, and every tag is an object in the DOM.
  • Nested tags are children of the enclosing one.
  • All these objects are accessible using JS, and we can use these to modify the page.
  • For example you can access the body tag with document.body

Resource: DOM nodes

Resource: Walking the DOM

JS in more depth

Useful design patterns / things to know

Objective

This is a quick primer into useful javascript design patterns.

These concepts will be useful because you will see them everywhere in frontend work.

Loading libraries via CDN

Easiest way import libraries is via a CDN (content delivery network)

JQuery:


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

D3:


<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.2/d3.min.js"></script>
                    

Other methods: downloading and importing yourself

Install as a package, using some module bundler to manage (e.g. npm, webpack)

Function chaining

Or why JQuery became popular

You could write this in plain vanilla JS:


var node = document.createElement("p");
var textnode = document.createTextNode("Hello World");
node.appendChild(textnode);
document.getElementById("main").appendChild(node);
                    

OR in JQuery


let para = $("<p>").text("hello world")
$("#main").append(para);
                    

Function chaining makes reading / writing code easier.

Function chaining 2

OR in D3


d3.select("#main").append(p).text("Hello World");
                    

You'll see function chaining everywhere in D3. Actually lots and lots of popular libraries (lodash, etc.) support function chaining.

JSON

JSON (Javascript Object Notation), sample code snippet:


let classroom = [
    {name: "Alfred", math: 90, english: 70 },
    {name: "Betty", math: 85, english: 30 },
    {name: "Cindy", math: 35, english: 60 }
];
                    

JSON — a collection of key / value pairs — has overtaken XML as a data structure for backend to communicate with frontend. You will see this everywhere.

Know how to access JSON key / value pairs.

Anonymous functions

Anonymous functions are functions without names.

It is usually not accessible after its initial creation. Often seen as arguments to other functions.


classroom.forEach(function(ele) {
    console.log(ele);
});
                    

OR you can use arrow notation (ES6):


classroom.forEach(ele => console.log(ele));
                    

Arrow notation is a shorthand for anonymous functions. Note that the two methods are not exactly synonomous (e.g. function scope). Most use cases it does not matter though.

Data manipulation - map, reduce, filter, etc.

Array functions for handling data(ES6). Or use a library like loadash for more use cases.


const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
console.log(words.filter(word => word.length > 6));
                    

AJAX, fetch, Axios

Different methods / design patterns of accessing HTTP resources, e.g. reading and writing (GET/POST) to a web API.

More detail: JQuery AJAX, fetch, Axios

For AJAX you can also use vanilla JS to write. Fetch is newer JS specification (ES6), and Axios is a popular promise-based HTTP client.

Simple code snippet for fetch:


fetch('https://api.data.gov.sg/v1/transport/carpark-availability')

  .then(response => response.json())
  .then(data => console.log(data));
                    

Callbacks, promises, async / await

Design patterns for handling the asynchronous nature of JS.

More detail: Callbacks, Promises(ES6), Async / Await (ES6)

You will mainly encounter asynchronous errors typically when you do get / post operations.

For example:


let myData = {};
fetch('https://api.data.gov.sg/v1/transport/carpark-availability')
  .then(response => response.json())
  .then(data => {myData = data});
console.log(myData);
                        

What is wrong with this code?

Async / await example


let myData = {};

async function fetchdata() {
    let response = await fetch('https://api.data.gov.sg/v1/transport/carpark-availability');
    let data = await response.json();
    return data;
}

fetchdata().then(data => {
    myData = data;
    console.log(myData);
})
                        

Questions?

Chi-Loong | V/R