Recap and Wrap up of CSS Flexbox
Introduction to Module 2 with JavaScript Basics
console.log
, Numbers, Strings, Arrays
openBox
Today, we will spend a bit of time with the Chrome console to explore the basics of JavaScript, just enough to demonstrate how to use it with the DOM to interact with a button on a simple web page.
Over next week, we'll get more practice with the different language basics (conditionals, loops, functions, etc.) but you can find a handy reference slide deck here.
HW1 due Wednesday, lock date Friday at 11PM.
Make sure to...
CP2 will be out Wednesday
Flex is a powerful way to create responsive page layouts
Really takes practice, but remember to use wireframes and the DOM!
Making an element a flex parent will unlock various flex properties to distribute across an axis and align down that axis.
The DOM tree is useful to focus only on the parent/children containers
Common bugs:
display: flex
on children instead of parent: Remember, the parent tells the children what
to do! (with occasional cases of flex children properties like flex-grow
)display: flex;
flex-direction
(default row
)justify-content
align-items
flex-wrap
Tip: Practice with this page and the Chrome Inspector using the next few slides.
Content
Words and images
Structure
HTML
Style
CSS
Behavior
JavaScript
How to write content for a webpage using HTML5
How to add styles to a webpage using CSS
and linking a CSS
file to an
HTML
file
How to inspect the HTML
and CSS
of web pages in the browser
(...also Git, some web accessibility, and some design/development strategies as budding web developers!)
A lightweight "scripting" programming language
Created in 1995 by Brendan Eich (original prototype created in 10 days and called LiveScript)
NOT related to Java other than name and some syntactic similarities...
Used to define interactivity for web pages.
Now that we know how to add content and styles to a web page, lets explore how to add responsive behavior
Over Module 2, we'll use these building blocks to dynamically update what you see on a web page in response to clicks, text input, timers, etc.
Client-side script: Code that runs on the user's computer and does not need a server to run (just a browser!).
Client-side JavaScript is usually run after HTML and CSS have been loaded on the browser (e.g. from a server response).
Often, this JavaScript manipulates the page or responds to user actions through "event handlers".
We can use write JavaScript functions to...
As an interpreted programming language, JS is great to interact with a line at a time (similar to Python, but very different than Java). Where do you start?
The easiest way to dive in is with the Chrome browser's Console tab in the same inspector tool you've used to inspect your HTML/CSS.
Until we learn how to interact with the HTML DOM with JS, we recommend experimenting with the following code examples using this console to get comfortable with the basic syntax and behavior.
console.log
Used to output values to the browser console, most often used to debug JS programs.
You can think of this as System.out.println
in Java or print
in Python.
console.log("message");
JS (template)
console.log("The answer is: " + 42);
JS (example)
alert
Functionalert("message");
JS (template)
alert("Your browser says hi!");
JS (example)
A JS function that pops up a dialog box with a message - not ideal in practice, but sometimes a recommended debugging tool when first learning JS. Don't include alert statements in any of your assignments.
// single-line comment
/**
* multi-line
* comment
*/
JS
Identical to Java's comment syntax
Recall: 3 comment syntaxes
HTML: <!-- comment -->
CSS/Java/JS: /* comment */
Java/JS: // comment
For functions and program files, we'll use JSDoc commenting with @param
and
@returns
, which is covered
in the Code Quality Guide here.
let name = expression;
JS (template)
let level = 23;
let accuracyRate = 0.99;
let name = "Pikachu";
JS (example)
Variables are declared with the let
keyword (case-sensitive).
You may also see var
used instead of let
- this is an
older convention with
weaker scope - DO NOT USE var
anywhere
CQG: Use camelCasing for variable (and function) names
let level = 23; // Number
let accuracyRate = 0.99; // Number
let name = "Pikachu"; // String
let temps = [55, 60, 57.5]; // Array
JS (example)
Types are not specified, but JS does have types ("loosely-typed")
Number
, Boolean
, String
,
Array
, Object
, Function
, Null
,
Undefined
If you've programmed in a statically-typed language like Java, you will recall that when declaring variables, you must specify their type which must always stay the same.
boolean isValid = "hello!"; // error
Java
In a dynamically-typed language like JavaScript, you don't need to specify the
type (just use let
or const
) and you may change the type the variable refers to later in execution.
let isValid = true; // no error
isValid = "hello!";
isValid = 1;
JS
This may seem to imply fewer errors in JS, but it's not uncommon to run into subtle (silent) bugs in your JS programs as a result!
let enrollment = 99;
let medianGrade = 2.8;
let credits = 5 + 4 + (2 * 3);
JS
Integers and real numbers are the same type (no int
vs. double
). All numbers in JS are floating point numbers.
Same operators: + - * / % ++ -- = += -= *= /= %=
and similar precedence to Java.
Many operators auto-convert types: "2" * 3
is 6
NaN
("Not a Number") is a return value from operations that have an undefined numerical result (e.g. dividing a String by a Number).
let nickName = "Sparky O'Sparkz"; // "Sparky O'Sparks"
let fName = nickName.substring(0, s.indexOf(" ")); // "Sparky"
let len = nickName.length; // 15
let name = 'Pikachu'; // can use "" or ''
JS
Methods:
charAt
,
charCodeAt
,
fromCharCode
,
indexOf
,
lastIndexOf
,
replace
,
split
,
substring
,
toLowerCase
,
toUpperCase
Escape sequences behave as in Java: \' \" \& \n \t \\
To convert between Numbers and Strings:
let count = 10; // 10
let stringedCount = "" + count; // "10"
let puppyCount = count + " puppies, yay!"; // "10 puppies, yay!"
let magicNum = parseInt("42 is the answer"); // 42
let mystery = parseFloat("Am I a number?"); // NaN
JS
To access characters of a String s
, use s[index]
or
s.charAt(index)
:
let firstLetter = puppyCount[0]; // "1"
let fourthLetter = puppyCount.charAt(3); // "p"
let lastLetter = puppyCount.charAt(puppyCount.length - 1); // "!"
JS
While Strings in JS are fairly similar to those you'd use in Java, there are a few special cases that you should be aware of.
length
is a property (not a method, as it is in Java)+
: 1 + 1
is 2
, but "1" +
1
and 1 + "1"
are both "11"
!
Practice: repeat
null
and undefined
let foo = null;
let bar = 9;
let baz;
/* At this point in the code,
* foo is null
* bar is 9
* baz is undefined
*/
JS
undefined
: declared but has not yet been assigned a value
null
: exists, but was specifically assigned an empty value or
null
. Expresses intentional a lack of identification.
A good motivating overview of
null
vs.
undefined
Note: This takes some time to get used to, and remember this slide if you get confused later.
let name = []; // empty array
let names = [value, value, ..., value]; // pre-filled
names[index] = value; // store element
JS (template)
let types = ["Electric", "Water", "Fire"];
let pokemon = []; // []
pokemon[0] = "Pikachu"; // ["Pikachu"]
pokemon[1] = "Squirtle"; // ["Pikachu", "Sqiurtle"]
pokemon[3] = "Magikarp"; // ["Pikachu", "Sqiurtle", undefined, "Magikarp"]
pokemon[3] = "Gyarados"; // ["Pikachu", "Sqiurtle", undefined, "Gyarados"]
JS (example)
Two ways to initialize an array
length
property (grows as needed when elements are added)
As you write JS programs, you may will run into some silent
bugs resulting from odd typing behavior in JS. Automatic type conversion, or coercion,
is a common, often perplexing, source of JS bugs (even for experienced JS programmers).
Why is this important to be aware of? You'll be writing programs which use variables and conditional logic. Knowing what is considered truthy/false and how types are evaluated (at a high level) can make you a much happier JS developer (some practice)
Examples of some "not-so-obvious" evaluations:
2 < 1 < 2;
// true
0 + "1" + 2;
// "012"
[] + [];
// ""
"1" / null;
// Infinity
[+!![]]+[[![]+!![]]];
// "11"
This is worth 3 minutes of your viewing pleasure. (starting at 1:20)
function name(params) {
statement;
statement;
...
statement;
}
JS (template)
function myFunction() {
console.log("Hello!");
alert("Your browser says hi!");
}
JS (example)
The above could be the contents of basics.js
linked to our
HTML
page
Statements placed into functions can be evaluated in response to user events
Practice:
fixErrors2
,
containsTwice
,
functionMystery1
,
sumUpTo
,
veryBestSong
function repeat(str, n) {
let result = str;
for (let i = 1; i < n; i++) {
result += str;
}
return result;
}
let repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."
JS (example)
public static String repeat(String str, int n) {
String result = str;
for (int i = 1; i < n; i++) {
result += str;
}
return result;
}
String repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."
Java (example)
function repeat(str, n) {
let result = str;
for (let i = 1; i < n; i++) {
result += str;
}
return result;
}
let repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."
JS (example)
def repeat(str, n):
result = str;
for i in range(1, n):
result = result + str;
return result;
repeatedStr = repeat("echo...", 3) // "echo...echo...echo..."
Python (example)
Now, we'll use these building blocks of a new programming language to control the behavior of our pages (which we don't get with HTML/CSS!).
In general, to add interactivity to our HTML/CSS websites we need to:
<head>
)
Image source (MDN) and recommended reading
So far, we have used Atom (or a similar editor) to write HTML/CSS for the structure/styles for our page. We will continue to use Atom to write JavaScript and add behavior.
As always, the webpage is rendered by the browser. We will add a link to our JS from HTML (similar to the idea of linking a CSS file) and the browser will execute the JS after the HTML/CSS has been loaded.
<script>
<script src="filename"></script>
HTML (template)
<script src="example.js"></script>
HTML (example)
The script
tag should be placed in the HTML
page's
head
.
All JavaScript code used in the page should be stored in a separate .js
file
JS code can be placed directly in the HTML
file's body
or
head
(like CSS
), but this is poor code quality. You should always separate content,
presentation, and behavior
Here's a basics.html linked to this basics.js - feel free to use these to practice with!
"use strict";
...your code...
JS
Writing "use strict";
at the very top of your JS file turns
on strict syntax checking:
You should always turn on strict mode for your code in this class!
A tree-shaped structure built out of all of the HTML elements in a page, accessible via JavaScript
A set of JavaScript objects that represent each element on the page
Each tag in a page corresponds to a JavaScript DOM object with properties (e.g. src
, classList
) and functions (e.g. addEventListener
)
Each element has properties and functions that JavaScript can use to examine elements' state
JavaScript is a language that lets us interact with a webpage document
We can use JS to...
Access and modify properties of elements...
boxImg.src = "star.png"
Add/remove/toggle classes...
boxImg.classList.add("bordered")
someInput.classList.toggle("highlighted")
Add/remove an "event listener"...
boxBtn.addEventListener("click", openBox);
We'll learn about each of these in the next few lectures!
Every JavaScript program can refer to the following global objects:
method | description |
---|---|
document | current HTML page and its content |
history | list of pages the user has visited |
location | URL of the current HTML page |
navigator | info about the web browser you are using |
screen | info about the screen area occupied by the browser |
window | the browser window |
Try typing each object in your console followed by "." - your browser will
try to autocomplete, and you can see what kind of information each global object
has! What kind of information do you get when typing
window.clientInformation
?
Usually, you'll just want to use document
(to access elements) and window
(to know when the page is loaded) in your JS programs
document
object in JavaScriptlet name = document.getElementById("id");
JS
document.getElementById
returns the DOM object for an element with a given
id
(note that you omit the #
when giving an id)
document.querySelector
to get elements by class name) Wednesday!For starters, the HTML attributes. This HTML:
<img src="images/puppy.png" alt="A fantastic puppy photo"/>
HTML
Has a DOM object (let's call it puppyImg
) with these two properties:
puppyImg.src
-- set by the browser to images/puppy.png
puppyImg.alt
-- set by the browser to "A fantastic puppy photo"
There are a ton of HTML tags that are used to build UI (user interfaces).
Enter Text: <input type="text" id="input-text" /> <Go!>
HTML
output
We'll start with the humble button today, but we'll learn a few more like input boxes and dropdowns next week.
<button>
<button id="my-btn">Click me!</button>
HTML
output
Text inside of the button
tag renders as the button text
To make a responsive button (or other UI controls):
Unlike Java programs, JS programs have no main
; they respond to user actions
called events
Event-Driven Programming: writing programs driven by user events
addEventListener
function handleFunction() {
// event handler code
}
// attaching a named function
element.addEventListener("click", handleFunction);
JS (onclick template)
click
Event Handler to Open the Mystery Box<img id="mystery-box" src="question-block.png" alt="A Mystery Box" />
<button id="box-btn">Click me!</button>
HTML
let boxBtn = document.getElementById("box-btn");
boxBtn.addEventListener("click", openBox);
function openBox() {
let box = document.getElementById("mystery-box"); // 1. Get the box image
box.src = "star.png"; // 2. Change the box image's src attribute!
}
JS
output
As we'll learn more about on Wednesday, we need to wrap any JS code that interacts with the document
inside the window's load
event handler. load
is the event listened to
on the window to indicate when the page "is loaded".
When the page is loaded, everything in the
attached function (in our example, we call this init
for "page initialization"),
is executed, including setting up the button's click
event listener.
// listener attached before page is loaded
window.addEventListener("load", init);
function init() {
// this code is ran after page is loaded!
let boxBtn = document.getElementById("box-btn");
boxBtn.addEventListener("click", openBox);
}
function openBox() {
let box = document.getElementById("mystery-box");
box.src = "star.png";
box.alt = "A star!";
}
mystery-box.js (commented example)
You can see the HTML output here. On Wednesday, we'll add one more important component to our JS files: the module pattern.