Forms, Events and Event Handlers


Goal

By the end of today, you will be able to:

  1. use the appropriate vocabulary to talk about events and event handlers
  2. define a function to act as an event handler
  3. attach it to the DOM

Function Review: Definition, Invocation, Parameters, Arguments

Imagine we have a function that will check to see if a triple of numbers are a Pythagorean triple, namely that:

a2+b2=c2

Here's the definition of the function:







(Can you think of a more succinct definition?)

Here are some invocations of the function:

isPythTriple(1,2,3);
isPythTriple(3,4,5);
isPythTriple(5,3,4);
isPythTriple(5,11,12);
isPythTriple(5,12,13);
x = 3; y = 4; z = 5;
isPythTriple(x,y,z);
isPythTriple(z,x,y);

Open up your JS console and try some!

Questions:

  • What's the difference between a definition and an invocation?
  • What's the difference between an argument and a parameter?
  • Does it matter what order the arguments are in?
  • How can you tell what value each parameter will have?
  • What does return do?

Purely Functional Functions

The isPythTriple function, above, has no side-effects. It doesn't pop up any alerts and it doesn't prompt for input. It doesn't modify the page. How can it do anything useful?

Actually, functions like that can be very useful, because they aren't tied to a particular problem. Maybe the argument values come from a form that the user fills out. Maybe they come from using prompt. Maybe they are numbers that are randomly generated, searching for more triples. It doesn't matter; this function will still accept them and report whether they meet the criteria.

The use of that return value is similarly undetermined. It might be reported to the user, it might be used to control a loop (stop looping when you find a triple), or it might be to grade an exam (did the user enter a correct triple?). Again, it doesn't matter. This function just does its job and doesn't worry about the larger context.

We will often do this. In fact, we did on the homework.

Hw6 Questions

Let's look at the following:

  • What does task 4 do? How does it get its input? What side-effects does it have? What does it do with its results?
  • What do tasks 1-3 do? How do they get their input? What side-effects do they have? What do they do with their results?

Recap

We learned about forms and event handlers.

Forms

  • The form tag is a wrapper for a set of inputs or controls.
  • Most controls use the input tag. There are some fancy new ones (with types like email or phone), but the old-fashioned type=text is universally supported.
  • Larger chunks of text can be entered with a textarea, with attributes of rows and cols.
  • Pull-down menus use the select tag, with each menu item using the option tag.
  • There's also a button tag, and its near twin, input type="button"
  • submit buttons submit the form. For now, we'll use type=button, for a button that is just a button. That's the one we'll attach an event handler to.

Event Handlers

  • An event handler is a function that is
    • attached to an element and associated with an event
    • is invoked by the browser when the event occurs with that element.
  • Event handlers typically take no arguments and return no values. They work entirely by side-effect.
  • While an event handler is executing, the special variable this is bound to the target of the event (for example, the element that was clicked on).

We also learned about jQuery's .val() method, which retrieves the value of a form control.

Pattern: Separating Calculation from Interface

In the events reading, we saw this example of a form to convert pounds to kilos:

kilograms

Here's the code:





Notice that we defined two separate functions. One is a generally useful function to convert pounds to kilograms; we could imagine using it in lots of problem-solving. The second is a very specific function to pull some data out of a particular form and insert an answer into a place on the page. It would be hard to imagine re-using this function elsewhere. However, it makes an excellent event-handler.

This pattern is very common. It's good practice to write code that is generally useful and could be re-used in other contexts and for other purposes. We can't do that if the code is intermingled with stuff that is very tied to a particular situation. So, we separate the problem-specific stuff from the general stuff.

Our Destination

We're going to build the following form: colorslider (instructor only).

No, I'm not going to show you the source code.

Quiz Question Nr. 1

Which of the following creates a slider from 0 to 100, with the initial value of 50?

  1. <input type="range" min=0 max=100 value=50>
  2. <input type="slider" start=0 finish=100 value=50>
  3. <input type="range" start=0 finish=100 value=50>
  4. <input type="slider" min=0 max=100 value=50>

Exercise 1: Build a Page with a Form

Build the page and form above. You can start with the following jsfiddle.

  • You won't need any JavaScript for this exercise; this one is pure HTML
  • Add the elements necessary to create the form.
  • Make sure to have a span that can hold the current slider value, one span for each slider
  • Give the span an ID so that you can change its contents. I think it's a good idea to give each slider an ID, too, though it's not strictly necessary.
  • Create a button, with type="button", that we'll later use to set the color.

Your solution might look like this: v1. Some notes on the solution:

  • You need a <form> tag as a wrapper for the whole form.
  • Form elements are inline, so we put them on different lines using the <p> tag.
  • We use the <span> element as a place to put the values we report. They can initially be empty.
  • The <label> elements are not required for the form to work. They're there to improve accessibility
  • The <button> tag creates the set color button. Currently it does nothing.

Quiz Question Nr. 2

Which of the following replaces the contents of a div whose ID is quest with the text "to seek the grail"?

  1. $(quest).html("to seek the grail");
    
  2. $("#quest").innerHTML("to seek the grail");
    
  3. $(".quest").html("to seek the grail");
    
  4. $("#quest").html("to seek the grail");
    

Quiz Question Nr. 3

Which of the following implements a button that says "Some call me ... Tim!" when clicked on?

Here's a demo:

  1. <button type="button" id="tim_button">what is your name?</button>
    function iamTim() {
       alert("Some call me ... Tim!");
    }
    $("#tim_button").onclick(iamTim);
    
  2. <button type="button" id="tim_button">what is your name?</button>
    function iamTim {
       alert("Some call me ... Tim!");
    }
    $("#tim_button").click(iamTim);
    
  3. <button type="button" id="tim_button">what is your name?</button>
    function iamTim() {
       alert("Some call me ... Tim!");
    }
    $("#tim_button").click(iamTim);
    
  4. <button type="button" id="tim_button">what is your name?</button>
    function iamTim() {
       alert("Some call me ... Tim!");
    }
    $("#tim_button").click(iamTim());
    

Observations:

  • When the script is read, the function is defined.
  • When we click on the button, the function is invoked.
  • The definition shows a pattern for how the function will be invoked.

Discussion:

  • We always use parens in the function definition.
  • We use parens after a function name when we invoke it.
  • When we attach it to an element as an event handler, we are not invoking it.

Quiz Question Nr. 4

Which of the following functions would copy the value of the red slider (ID is Rslider) to the span whose ID is redVal?

  1.     function showRed() {
            var rVal = $("#Rslider").val();
            $("#redVal").html = rVal;
        }
    
  2.     function showRed() {
            var rVal = $("#Rslider").value();
            $("#redVal").html(rVal);
        }
    
  3.     function showRed() {
            var rVal = $("#Rslider").val();
            $("#redVal").html(rVal);
        }
    
  4.     function showRed() {
            var rVal = $("#redVal").val();
            $("#Rslider").html(rVal);
        }
    

Exercise 2: Add functions to update slider values

  • If you didn't finish the previous exercise, copy/paste my solution to your jsfiddle and use that. Or, you can use this jsfiddle #2
  • Define a function like showRed above that looks up the value of the red slider and inserts it into the appropriate span.
  • You can also visit my solution to ex1 and use the JS console to test your function by hand.
  • Add the function as an event handler for the onChange event on the slider, using jQuery's change method:
     $(selector).change(func); 
  • Once it works, add similar ones for green and blue.

Your solution might work like this: v2a

The hexByte function

The activities on functions, last week, included the development of a hexByte function. Here's a different implementation, using the fact that numbers have a .toString() method that takes as its argument the number base to convert to.

Open the JS console and try some of the following:

var a = 7; a.toString(16);
var b = 11; b.toString(16);
var c = 17; c.toString(16);
var d = 255; d.toString(16);

Here's the definition of a hexByte function that does that and a little bit more, returning a 2-digit string in hexadecimal. It also ensured that the value is a number by using parseInt().







Open the JS console and try some of these:

hexByte(2);
hexByte(55);
hexByte(255);

Exercise: hexColor function

Define a function named hexColor that takes three parameters, one for each color primary, and returns a color specification using the hexadecimal notation, like #3399FF. Don't forget to glue on the leading hash mark. The return value will be a string. Feel free to use the hexByte function if that's useful. (Hint: it is.)

// function definition here





// sample output:
alert( hexColor(51, 128, 255) ); // should be #3380ff
alert( hexColor(0, 9, 192) ); // should be #0009C0

Your solution might look like this:

function hexColor(red,green,blue) {
    return "#"+hexByte(red)+hexByte(green)+hexByte(blue);
}

// sample output:
alert( hexColor(51, 128, 255) ); // should be #3380ff
alert( hexColor(0, 9, 192) ); // should be #0009C0
  

Thank goodness for functions! Think of what a mess that code would be if we didn't have the hexByte function! That function makes the code for hexColor clear, concise and correct.

Long Exercise: Processing Color Values

Do the following, testing after each step.

  1. If you didn't finish the previous exercise, save my solution to your desktop and use that for this exercise, or copy/paste it to your jsfiddle: v2a.

    Or, use this jsFiddle #3

  2. Define a function called setColorthat looks up the numeric value of each slider (hint, use parseInt on the value).
  3. The function should then use hexColor to convert it to a color string.
  4. The function takes the finished string and inserts it into the color value span.
  5. The function takes the finished string and assigns it as the value of the background-color CSS property of the #box.
  6. Add the finished function as an event handler for the click event on the set color button, using the jQuery $(...).click(func) method.

Your solution might work like this: v5d or this: jsFiddle #4

Summary

We hope that after these activities you have a good understanding of:

  • Defining and invoking functions.
  • Using functions as event handlers.
  • Using jQuery to modify a page and attach event handlers.
  • Defining functions that return a value

Solutions

Will be posted later, visit again after .

Quiz questions:

1. A
2. D
3. C
4. C

© Wellesley College Computer Science Staff. This work is licensed under a Creative Commons License. Date Modified: Wednesday, 11-Oct-2017 13:27:19 EDT