Reminders
(Brief) Notes on Lecture
Example Quiz Question
CSS Recap
JavaScript
HW1 is out now, due next week. Assessment on HTML and CSS.
CP1 was due last night, can still be turned in late until Thursday night.
OH and WPL available for questions. Check the calendar for times, Ed for Zoom links.
Quiz 1 will release at 3:00pm after lecture today. Will be available for 24 hours.
We'll be spending a lot of time in Chrome and in Chrome's DevTools.
Slides are here largely for reference.
Flex is a powerful way to create responsive page layouts
Really takes practice, but remember to use sketches, the DOM, and the inspector!
Making an element a flex parent will unlock various flex properties to distribute across an axis and align down that axis.
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");
console.log("The answer is: " + 42);
alert
Functionalert("message");
alert("Your browser says hi!");
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
*/
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;
let level = 23;
let accuracyRate = 0.99;
let name = "Pikachu";
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
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
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;
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);
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 String).
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 ''
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
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); // "!"
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
*/
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
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"]
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;
}
function myFunction() {
console.log("Hello!");
alert("Your browser says hi!");
}
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..."
}
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..."
}
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..."
}
def repeat(str, n):
result = str;
for i in range(1, n):
result = result + str;
return result;
repeatedStr = repeat("echo...", 3) // "echo...echo...echo..."
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 VSCode (or a similar editor) to write HTML/CSS for the structure/styles for our page. We will continue to use VSCode 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>
<script src="example.js"></script>
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!
document
object in JavaScriptlet name = document.getElementById("id");
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"/>
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!>
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>
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);
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>
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!
}
"use strict";
...your code...
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!
Especially if you're watching a recording, write your question on PollEverywhere and I'll answer them at the start of next lecture.
Either on your phone or computer, go to PollEv.com/robcse