CSE 154

Lecture 6: Intro to JavaScript

skelton

Agenda

Wrapping up Page Layout: Positioning

Introduction to JavaScript

  • History and motivation
  • Introduction to data types, conditionals, and loops
  • Introduction to JS functions
  • Getting started with JS on a webpage and handling a click event!

Administrivia Note: Exam dates/locations are now finalized! Midterm is October 26th, 5:15-6:15PM (1 hour) in Kane 110. Details and resources will be posted as we get closer to the exam.

A Note About Naming in Windows

Please make sure an file names you reference (e.g. html, css, images) in your HTML are all-lowercase (and have no spaces). Windows will ignore casing, but they will appear as broken links on other systems!

Example, if you have an image under "images/pupper.jpg" relative to your HTML file, the first image will render but he second will appear broken on non-Windows systems:

<img src="images/pupper.jpg" alt="my pupper!" />
<img src="images/pupper.JPG" alt="my pupper!" />

HTML

One more thing on copyright

What if I wanted to add an image to the background of an element, like my page body, how should I do that? How should I cite that?

Cite in the .css file where the image is being used.

body {
  /* This image was purchased from
     https://www.istockphoto.com/us/vector/seamless-vector-pattern-traces-of-paws-gm539440756-96166041
     and thus under this license agreement https://www.istockphoto.com/legal/license-agreement */
  background-image: url("paw.jpg");
}

CSS

Positioning Background Images

We've seen some CSS rules for styling backgrounds of elements.

When you have an image you want to appear behind text or other page elements, it's often best to use the background-image which sometimes is used with backgroud-repeat and/or background-position.

Positioning Background Images: Example

body {
  background-image: url("paw.jpg");
  background-repeat: no-repeat;
  background-size: 200px 200px; /* when you need to change image size */
  /* 170px for start x-position, 20px for start y-position,
     top-left corner is (0, 0) */
  background-position: 170px 20px; /* try not to hardcode values... */
}

CSS (codepen)

This is the first paragraph

This is the second paragraph... try to make sure text in front of background images is readable!

output

Position values consist of two tokens (x and y), each of which can be top, left, right, bottom, center, a percentage, or a length value in px, pt, etc.

Position values can be negative to shift left/up by a given amount, but keep responsive page dimensions in mind

Recall: Layout Techniques in CSS

  • Appropriate use of Block vs. Inline elements and nesting in HTML
  • Box Model (margin/padding/border)
  • Flex
  • Positioning
  • Float (less common today, but still good to know)

Every so often, you'll find positioning useful to fix elements on the page relative to some other element (or the screen boundaries). We'll do a quick demo on how to do this properly (you may find it helpful on your HW).

positioning Elements

position: static
Default value. Elements render in order, as they appear in the document flow
position: fixed
Puts an element at an exact position within the browser window
position: absolute
Puts an element at an absolute position based on the location of the element's parent container
position: relative
Makes children positioned relative to the parent container

Positioning Example

#menubar {
  position: absolute; /** fixed */
  left: 450px;
  top: 60px;
}

CSS

<div id="menubar">Menu stuff!</div>

HTML

Puts a menu bar on the screen 450px from the left, and 60px down from the top.

Strategies for page layout

  1. Hit your head against the desk
  2. Crawl into a foetal position and cry your eyes out
  3. Try some position: _________________ and float: _________ styles.
  4. Test and realize that didn't work.
  5. Hit your head against the desk again.
  6. Look it up in stack overflow. Get really confused.
  7. Throw some of that code in your css file.
  8. Test that and realize it didn't work.
  9. Play with Flexbox Froggy.
  10. Come back to your page with flex magic.
  11. Never look back (ok, there is such thing as flex overkill...).
Peter CSS gif

from https://imgur.com/gallery/Q3cUg29

Seriously... Strategies for page layout

First try box model, text-align, vertical-align

Next try flex boxes. Powerful way to build many different layouts in a page.

Special Use Cases:

Use position: absolute|fixed|relative only when you want complete control over where things go

Use float only when you want to remove an element from the flow, and wrap text around it

What We've Learned So Far

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

Git!

CSE 154 Modules

  1. Webpage structure and appearance with HTML5 and CSS.
  2. Client-side interactivity with JS DOM and events.
  3. Using web services (API's) as a client with JS.
  4. Writing JSON-based web services with PHP.
  5. Storing and retreiving information in a database with MySQL and server-side programs.

Motivating Module 2: Think, Pair, Share

On notecards, please write down:

  1. What are three examples of "interactive" features you've used or seen on webpages?
  2. What's one feature involving user interaction on a webpage you would like to learn how to implement (be specific or general)?
    Example: "I would like to learn how to implement a todo-list manager on my webpage!"

Note: We will collect these at the end of the class (optional) - we might add some creative ideas to additional section exercises!

Webpage Behavior with JavaScript

Now that we know how to add content and styles to a web page, lets explore how to add responsive behavior

These slides will introduce the basics of the JavaScript language:

  • As a client-side scripting language
  • Variables and Types
  • Conditional statements and Loops
  • Functions
  • Simple click event handling

Soon, we'll use these building blocks to dynamically update what you see on a web page in response to clicks, text input, timers, etc.

Terminology: Client-Side Scripting

client-side scripting

Client-side script: Code that runs on the user's computer. Client-side JavaScript is 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".

You don't need to have a server running to run client-side code - you can get started programming in JavaScript (our client-side scripting language) right away in your browser of choice!

What is JavaScript?

A lightweight "scripting" programming language

Created in 1995 by Brendan Elch (original prototype created in 10 days and called LiveScript)

Used to make web pages interactive:

  • Insert dynamic text into HTML (ex: username)
  • React to events (ex: page load, user's mouse click)
  • Get information about a user's computer (ex: what browser they are using)
  • Perform calculations on user's computer (ex: form validation)

A web standard (but not supported identically by all browsers)

NOT related to Java other than name and some syntactic similarities...

Can be used in the browser, as well as Adobe Photoshop, embedded computers, the Unix terminal, etc. (we will be using it in the browser)

Following Along

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 browser's Console tab in the same inspector tool you've used to inspect your HTML/CSS.

Chrome Console

Until we learn functions to interact with the HTML DOM with JS, we recommend experimenting with the following code examples using this console to get comfortable with the fundamental syntax and behavior of the language.

Our First JavaScript Statement: alert

alert("message");

JS (template)

            alert("IE6 detected. Suck-mode enabled.");

JS (example)

never use internet explorer

A JS command that pops up a dialog box with a message - not ideal in practice, but a good debugging tool when first learning JS

Output in JS: console.log

Used to output values to the browser console (can view in your browser's dev tools under "Console").

Often preferred over alert to debug JS programs.

console.log("message");

JS (template)

console.log("The answer is: " + 42);

JS (example)

console.log example

Comments (same as Java)

// 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, which will be introduced when we learn how to write JS functions (next lecture).

Practice: commentSyntax, commentary

Variables and types

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, and you should use let in this class

Use camelCasing for variable (and function) names

Types are not specified, but JS does have types ("loosely-typed")

A Note about Declaring Types in JavaScript

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!

"Constants" in JavaScript

Since ECMA6, JavaScript has a special keyword to declare "constant" values. You should use these over the let keyword for variables that are not intended to ever be updated (similar to constants in Java).

Use UPPER_CASING naming conventions to denote const in JS.

let month = 12;
month = 1; // no error

const COOLEST_CLASS = "CSE154";
COOLEST_CLASS = "clazz"; // error

JS

These can help avoid some of the bugs mentioned on the previous slide (an error occurs when trying to reassign a const).

Number Type

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: + - * / % ++ -- = += -= *= /= %=

Similar precedence to Java

Many operators auto-convert types: "2" * 3 is 6

Practice!

String type

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

More about Strings

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

Common Bugs when Using Strings

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.

  • Remember that length is a property (not a method, as it is in Java)
  • Concatenation with +: 1 + 1 is 2, but "1" + 1 and 1 + "1" are both "11"!

Practice: repeat, containsTwice

Math object

            let rand1to10 = Math.floor(Math.random() * 10 + 1);
let three = Math.floor(Math.PI);

JS

Methods: abs, ceil, cos, floor, log, max, min, pow, random, round, sin, sqrt, tan

Properties: E, PI

for Loops (same as Java)

for (initialization; condition; update) {
  statements;
}

JS (template)

            let sum = 0;
for (let i = 0; i < 100; i++) {
  sum = sum + i; // same as sum += i;
}

JS (example)

let s1 = "It's a-me, Mario!";
let s2 = "";
for (let i = 0; i < s.length; i++) {
  s2 += s1[i] + s1[i];
}
// s2 stores "IItt''ss  aa--mmee,,  MMaarriioo!!"

JS (example)

See below slides for comparisons in Java/Python

for Loop Comparisons

let s1 = "It's a-me, Mario!";
let s2 = "";
for (let i = 0; i < s.length; i++) {
  s2 += s1[i] + s1[i];
}
// s2 stores "IItt''ss  aa--mmee,,  MMaarriioo!!"

JS (example)

String s1 = "It's a-me, Mario!";
String s2 = "";
for (int i = 0; i < s.length(); i++) {
  s2 += s1.charAt(i) + s1.charAt(i);
}

Java (example)

s1 = "It's a-me, Mario!";
s2 = "";
for i in range(len(s1)):
    s2 += s1[i] + s1[i];

Python (example)

if/else Statements (same as Java)

if (condition) {
  statements;
} else if (condition) {
  statements;
} else {
  statements;
}

JS

Identical structure to Java's if/else statements

JavaScript allows almost anything as a condition

Practice: rockPaperScissors

while loops (same as Java)

while (condition) {
  statements;
}

JS

do {
  statements;
} while (condition);

JS

break and continue keywords also behave as in Java but do not use them in this class!

Practice: loopMystery6

Logical Operators

Relational: > < >= <=

Logical: && || !

Equality: == != === !==

  • Most logical operators automatically convert types. These are all true:
    • 5 < "7"
    • 42 == 42.0
    • "5.0" == 5
  • The === and !== are strict equality tests; checks both type and value: "5.0" === 5 is false. It's usually a good idea to use === instead of ==.
  • What does 154 === 154.0 evaluate to?

Helpful JavaScript equality table!

Boolean Type

            let iLikeJS = true;
let ieIsGood = "IE6" > 0; // false
if ("web dev is great") { /* true */ }
if (0) { /* false */ }
if (1) { /* true */ }

JS

Any value can be used as a Boolean

  • "falsey" values: false, 0, NaN, "", null, and undefined
  • "truthy" values: anything else

Understanding what is "falsey" vs. "truthy" takes patience and practice.

When in doubt, check in the browser console!

Special Values: 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

Arrays

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)

Array methods

let a = ["Mario", "Luigi"]; // [Mario, Luigi]
a.push("Koopatroopa");      // [Mario, Luigi, Koopatroopa]
a.unshift("Bowser");        // [Bowser, Mario, Luigi, Koopatroopa]
a.pop();                    // [Bowser, Mario, Luigi]
a.shift();                  // [Mario, Luigi]
a.sort();                   // [Luigi, Mario]

JS

Array serves as many data structures: list, queue, stack, ...

Methods: concat, join, pop, push, reverse, shift, slice, sort, splice, toString, unshift

  • push and pop add/remove from back
  • shift and unshift add/remove from front
  • shift and pop return the element that is removed

Practice: findMin , switchPairs

Splitting strings: split and join

let s = "the quick brown fox";
let a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse();          // ["fox", "brown", "quick", "the"]
s = a.join("!");      // "fox!brown!quick!the"

JS

split breaks apart a String into an array using a delimiter

  • Can also be used with regular expressions surrounded by /:
    let a = s.split(/[ \t]+/);

join merges an array into a single String, placing a delimiter between them

Defining Functions

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

From the Console to a .js File

Linking to a JavaScript file: <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.

Note: Before HTML5, it was required to use a type="text/javascript" in the script tag. In HTML5, this is recommended against, since it's a redundant MIME type.

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 an basics.html linked to this basics.js - feel free to use these to practice with!

Event-Driven Programming

event-driven programming

Unlike Java programs, JS programs have no main; they respond to user actions called events

Event-Driven Programming: writing programs driven by user events

Common Types of JavaScript Events

Name Description
click A pointing device button (e.g. mouse) has been pressed and released on an element
dblclick A pointing device button is clicked twice on an element
keydown Any key is pressed down
keyup Any key is released
mouseenter A pointing device is moved onto an element that has the attached
mouseover A pointing device is moved onto the element that has the listener attached to itself or one of its children
mousemove A pointing device is moved over an element
mousedown A pointing device button is pressed on an element
mouseup A pointing device button is released over an element

We'll cover more later (you can find a full list here), but today we'll demo click!

Handling Events with addEventListener

function handleFunction() {
  // event handler code
}
// attaching a named function
element.addEventListener("click", handleFunction);

JS (onclick template)

  • JavaScript functions can be set as event handlers
  • When you interact with the element, the function will execute
  • You can also attach events with element.onclick (see example and more information on slide below)

Older Alternative: onevent handlers

Example with onclick (same effect as previous slide):

// attaching a named function
function handleFunction() {
  // event handler code
}
element.onclick = handleFunction;

JS (onclick template)

The newer addEventListener is preferred as it lets you easily remove a listener to a specific event on an element, and it also lets you add multiple functions to an event listener. For this example, that doesn't make a difference, but we will see examples where it does!

More information about tradeoffs here.

Accessing Elements from the Document in JavaScript

Accessing an Element by ID

let 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)
  • We'll learn about other ways to get DOM elements (e.g. by class) tomorrow and Wednesday!

Back to HTML with Buttons: <button>

            <button id="my-btn">Click me!</button>

HTML

output

Button's text appears inside tag; can also contain images

To make a responsive button or other UI control:

  1. Choose the control (e.g., button) and event (e.g., mouse click) of interest
  2. Write a JavaScript function to run when the event occurs
  3. Attach the function to the event on the control

Right now this button doesn't do anything when we click it. That's because it doesn't have event handler code attached :( Let's see an example where we do have an event listener attached to a button on our page!

click Event Handler: an Example

<img id="pokeball" src="images/pokeball.jpg" alt="a pokeball" />
<button id="demo-btn">Click me!</button>

HTML

let demoButton = document.getElementById("demo-btn");
demoButton.addEventListener("click", changeImage);

function changeImage() {
  let pokeballImg = document.getElementById("pokeball");
  pokeballImg.src = "images/mystery.gif";
}

JS

a pokeball

output

Putting it All Together

We'll learn more about this tomorrow, but in order for our JS to work when attached to an HTML file, we need to wrap any 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 main), is executed, including any click attachments!

// listener attached before page is loaded
window.addEventListener("load", main);

function main() {
  // this code is "unlocked" after page is loaded!
  let demoButton = document.getElementById("demo-btn");
  demoButton.addEventListener("click", changeImage);
}

function changeImage() {
  let pokeballImg = document.getElementById("pokeball");
  pokeballImg.src = "images/mystery.gif";
}

button-example.js (example)

You can see the HTML output here. On Wednesday, we'll add one more important component to our JS files: the module pattern.

Resources and Tips

Review programming basics: using variables, arrays, loops, if-statements, and functions

Go over some JavaScript tutorials - there are many great ones!

Practice! We now have JavaScript problems on Practice-It (80+ problems) and its sister site CodeStepByStep (200+ problems).

Check out cool examples of JavaScript on the web!