CSE 154

Lecture 8: Forms and Events

What we've Covered in JavaScript so Far

Types (Strings, Numbers, Arrays)

Conditionals, Loops, Functions

Modular JS Pattern

Basic Event Handlers

Today: More Events, Forms, Timers, and Animations

JavaScript "strict" mode


"use strict";
        
...your code...
          

JS

Writing "use strict"; at the very top of your JS file turns on strict syntax checking:

  • Shows an error if you try to assign to an undeclared variable
  • Stops you from overwriting key JS system libraries
  • Forbids some unsafe or error-prone language features

You should always turn on strict mode for your code in this class!

JS Skeleton


 

            

HTML


"use strict";
(function() {

  // set-up code that doesn't involve the DOM 
  //   (e.g. setting up initial values, arrays, etc.)

  window.onload = function() {
    // phew! your code goes here
  };

  //function definitions go here

})();
            

JS

Timers

Used to delay or set intervals for executing functions

Setting a Timer

method description
setTimeout(function, delayMS) arranges to call given function after given delay in ms
setInterval(function, delayMS) arranges to call function repeatedly every delayMS ms
clearTimeout(timerID)
clearInterval(timerID)
stops the given timer

Both setTimeout and setInterval return an ID representing the timer

  • This ID can be passed to clearTimeout/Interval later to stop the timer

setTimeout Example


          
          
          

HTML


          window.onload = function() {
            document.getElementById("clickme").onclick = delayedMessage;
          };

          function delayedMessage() {
            document.getElementById("outputText").innerHTML = "Wait for it...";
            setTimeout(sayBooyah, 5000);
          }

          function sayBooyah() { // called when the timer goes off
            document.getElementById("outputText").innerHTML = "BOOYAH!";
          }
          

JS

output

setInterval Example


          let timer = null; // stores ID of interval timer
          function delayMsg2() { 
              timer = setInterval(mowgli, 1000);
          }

          function mowgli() {
            document.getElementById("outputText").innerHTML += "Mowgli!"
          }
          

JS

output

clearInterval Example


          let timer = null; // stores ID of interval timer
          function toggleDelayMessage() { 
            if (timer === null) {
              timer = setInterval(mowgli, 1000);
            } else {
              clearInterval(timer);
              timer = null;
            }
          }

          function mowgli() {
            document.getElementById("outputText").innerHTML += "Mowgli!"
          }
          

JS

output

Passing Parameters to Timers


          function delayedMultiply() {
            // 6 and 7 are passed to multiply when timer goes off
            setTimeout(multiply, 2000, 6, 7);
          }

          function multiply(a, b) {
            alert(a * b);
          }
          

JS

Any parameters after the delay are eventually passed to the timer function

  • Doesn't work in IE; must create an intermediate function to pass the parameters

Why not just write this?


          setTimeout(multiply(6, 7), 2000);
          

JS

Common Timer Errors

Many students mistakenly write () when passing the function


          setTimeout(booyah(), 2000);
          setTimeout(booyah, 2000);

          setTimeout(multiply(num1, num2), 2000);
          setTimeout(multiply, 2000, num1, num2);
          

JS

What does it actually do if you have the ()?

  • It calls the function immediately, rather than waiting the 2000ms!

Checkboxes: <input>

yes/no choices that can be checked and unchecked (inline)


           Lettuce
           Tomato
           Pickles
          

HTML

Lettuce Tomato Pickles

output

None, 1, or many checkboxes can be checked at same time

When sent to server, any checked boxes will be sent with value on:

  • http://webster.cs.washington.edu/params.php?tomato=on&pickles=on

Use checked="checked" attribute in HTML to initially check the box

Radio buttons: <input>

sets of mutually exclusive choices (inline)


           Visa
           MasterCard
           American Express
          

HTML

Visa MasterCard American Express

output

Grouped by name attribute (only one can be checked at a time)

Must specify a value for each one

Text labels: <label>


          
          
          
          

HTML

associates nearby text with control, so you can click text to activate control

can be used with checkboxes or radio buttons

label element can be targeted by CSS style rules

Drop-down list: <select>, <option>

menus of choices that collapse and expand (inline)


          
          

HTML

output

Option element represents each choice

Select optional attributes: disabled, multiple, size

Optional selected attribute sets which one is initially chosen

Using <select> For Lists


          
          

HTML

output

Optional multiple attribute allows selecting multiple items with shift- or ctrl-click

Must declare parameter's name with [] if you allow multiple selections

Option tags can be set to be initially selected

Option Groups<optgroup>


          
          

HTML

output

What should we do if we don't like the bold appearance of the optgroups?

Grouping Input: <fieldset>, <legend>

groups of input fields with optional caption (block)


          
Credit cards: Visa MasterCard American Express

HTML

Credit cards: Visa MasterCard American Express

output

Fieldset groups related input fields, adds a border; legend supplies a caption

Styling Form Elements


          element[attribute="value"] {
            property: value;
            property: value;
            ...
            property: value;
          }
          

CSS (template)


          input[type="text"] {
            background-color: yellow;
            font-weight: bold;
          }
          

CSS (example)

output

Attribute selector: matches only elements that have a particular attribute value

Useful for controls because many share the same element (input)

The innerHTML Property


          
          Hello 
          

HTML


          function addText() {
            let span = document.getElementById("output");
            span.innerHTML += " ... goodbye";
          }
          

JS

Hello

output

Can change the text inside most elements by setting the innerHTML property

Abuse of innerHTML

            
            // bad style!
            let paragraph = document.getElementById("welcome");
            paragraph.innerHTML = "text and <a href=\"page.html\">link</a>";
            

JS

innerHTML can inject arbitrary HTML content into page

However, this is prone to bugs and errors and is considered poor style

We forbid using innerHTML to inject HTML tags; inject plain text only

  • Later, we'll see a better way to inject content with HTML tags in it

The Six Global DOM Objects

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