Course Logistics

HW 2 is out (layouts and flexboxes): Due next Tuesday (April 11th)

Part 2 of the Creative Project is due Saturday night (April 8th). Have fun with it!

What We've Learned So Far

How to write content for a webpage using HTML

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

Today: JavaScript

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

Terminology: Client-Side Scripting

client-side scripting

Client-side script: Code runs in browser after page is sent back from server. Often, this code manipulates the page or responds to user actions.

What is JavaScript?

A lightweight programming language ("scripting language")

Created in 1995 by Brendan Elch (originally called LiveScript)

Used to make web pages interactive:

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

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

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

JavaScript vs. Java

Interpreted, not compiled (huh?)

More relaxed syntax and rules

JavaScript's key construct is the function rather than the object/class.

Contained within a web page and integrates with its HTML/CSS content

Linking to a JavaScript file: <script>

              
                
              
            

HTML

              
                
              
            

HTML

The script tag should be placed in the HTML page's head

Script code is stored in a separate .js file

JS code can be placed directly in the HTML file's body or head (like CSS)

Our First JavaScript Statement: alert

            
              alert("message");
            
          

JS

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

JS

never use internet explorer

A JS command that pops up a dialog box with a message

Variables and types

            
            var name = expression;
            
          

JS

            
            var level = 23;
            var accuracyRate = 0.99;
            var name = "Pikachu";
            
          

JS

Variables are declared with the var keyword (case-sensitive)

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

Number type

            
            var enrollment = 99;
            var mediangrade = 2.8;
            var credits = 5 + 4 + (2 * 3);
            
          

JS

Integers and real numbers are the same type (no int vs. double)

Same operators: + - * / % ++ -- = += -= *= /= %=

Similar precedence to Java

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

String type

            
            var nickName = "Sparky O'Sparkz"
            var fName = nickName.substring(0, s.indexOf(" ")); // "Sparky"
            var len = nickName.length;                         // 15
            var name = 'Pikachu';                              // can use " " or ' '
            
          

JS

Methods: charAt, charCodeAt, fromCharCode, indexOf, lastIndexOf, replace, split, substring, toLowerCase, toUpperCase

length is a property (not a method, as it is in Java)

Concatentation with +: 1 + 1 is 2, but "1" + 1 is "11"

More about Strings

Escape sequences behave as in Java: \' \" \& \n \t \\

To convert between numbers and Strings:

            
            var count = 10;                              // 10
            var stringedCount = "" + count;              // "10"
            var puppyCount = count + " puppies, yay!";   // "10 puppies, yay!"
            var magicNum = parseInt("42 is the answer"); // 42
            var mystery = parseFloat("Am I a number?");  // NaN
            
          

JS

To access characters of a String, use [index] or charAt:

            
            var firstLetter = puppyCount[0];                            // "1"
            var fourthLetter  = puppyCount.charAt(3);                   // "p"
            var lastLetter  = puppyCount.charAt(puppyCount.length - 1); // "!"
            
          

Comments (same as Java)

            
            // single-line comment

            /* multi-line comment */
            
          

JS

Identical to Java's comment syntax

Recall: 4 comment syntaxes

Practice: commentary

for loop (same as Java)

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

JS

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

JS

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

JS

Math object

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

JS

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

Properties: E, PI

Logical Operators

Relational: > < >= <=

Logical: && || !

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

Boolean Type

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

JS

Any value can be used as a Boolean

Converting a value into a Boolean explicitly:

Special Values: null and undefined

          
          var foo = null;
          var bar = 9;
          var baz;

          /* At this point in the code,
               foo is null
               bar is 9
               baz is undefined */
          
        

JS

undefined: has not been declared, does not exist

null: exists, but was specifically assigned an empty or null value

Why does JavaScript have both of these?

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

Arrays

          
          var name = [];                          // empty array
          var names = [value, value, ..., value]; // pre-filled
          names[index] = value;                   // store element
          
        

JS

          
          var types = ["Electric", "Water", "Fire"]; 
          var pokemon = [];
          pokemon[0] = "Pikachu";
          pokemon[1] = "Squirtle";
          pokemon[4] = "Magikarp";
          pokemon[4] = "Gyarados";
          
        

JS

Two ways to initialize an array

length property (grows as needed when elements are added)

Array methods

          
          var 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

Practice: findMin, switchPairs

Splitting strings: split and join

          
          var s = "the quick brown fox";
          var 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

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

Defining functions

          
          function name() {
            statement;
            statement;
            ...
            statement;
          }
          
        

JS

          
          function myFunction() {
            alert("Hello!");
            alert("Your browser says hi!");
          }
          
        

JS

The above could be the contents of example.js linked to our HTML page

Statements placed into functions can be evaluated in response to user events

Practice: functionMystery1, sumUpTo, veryBestSong

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

Event Handlers

          
            <element attributes onclick="function();">...
          
        

HTML

          
            <div onclick="myFunction();">Click me!</div>
          
        

HTML

Click me!

output

JavaScript functions can be set as event handlers

When you interact with the element, the function will execute

onclick is just one of many event HTML attributes we'll use

Buttons: <button>

          
            <button onclick="myFunction();">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

Accessing an Element: document.getElementById

            
            var 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.getElementById: An Example

            
            <img id="icon01" src="images/pokeball.jpg" alt="a pokeball" />
            <button onclick="changeImage();">Click me!</button>
            
          

HTML

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

JS

a pokeball

output

<input>

          
          <!-- 'q' happens to be the name of Google's required paramter -->
          <input type="text" name="q" value="Colbert Report" />
          <input type="submit" value="Booyah!" />
          
        

HTML

output

Input element is used to create many UI controls (an inline element that must be self-closed

name attribute specifies name of query parameter to pass to server

type can be button, checkbox, file, hidden, password, radio, reset, submit, text, ...

value attribute specifies control's initial text

<input> Text Fields

          
          <input type="text" size="10" maxlength="8" /> NetID <br />
          <input type="password" size="16" /> Password
          <input type="submit" value="Log In!" />
          
        

HTML

NetID
Password

output

input attributes: disabled, maxLength, readonly, size, value

size attribute controls onscreen width of text field

maxlength limits how many characters the user is able to type into the field

Text boxes: <textarea>

          
          <textarea rows="4" cols="20">
          Type your comments here.
          </textarea>
          
        

HTML

output

Initial text is placed inside textarea tag (optional)

Required rows and cols attributes specify height/width in characters

optional readonly attribute means text cannot be modified