One of the important features of almost all programming languages is the ability to store a value so that it can be used later. These are called variables.
There are rules for how they can be created and named. Here are the rules for JavaScript:
var
. JavaScript allows
this to be optional, but you should not.
weirdand no spaces.
specialpart of the language, such as
var
, or function
or if
, etc. These are reserved.
Make your variable names intuitive: they should
remind you of the stuff stored in them, so user_age
is good, but n
or stuff
is not.
What does the following statement do?
x = y;
It gets an error
It tests whether the two variables are equal
It copies the value of y
into x
It copies the value of x
into y
In this course, variables will almost always get their values from
We want some code that will ask the user their name and greet them. Which of the following does that?
var user = alert("what's your name?"); prompt("Greetings, "+user);
var user = prompt("what's your name?"); alert("Greetings, "+user);
var user = prompt("what's your name?"); var greet = "Greetings, "+user; alert(greet);
var user = alert("what's your name?"); var greet = "Greetings, "+user; prompt(greet);
There's a pattern to that kind of code:
Not all of our code will show that pattern, but it often will, so it's worth stepping back to see the pattern.
Forms allow the user to supply the information we want on their schedule, skipping around and ignoring inputs. That's much better than a series of prompts.
We can access anything in the document from JavaScript using the Document Object Model or DOM. The DOM is just a collection of stuff added to the JS language that lets us poke around in the document, finding the parents and children of nodes, and even modifying the document.
We can also find out dynamic info like the value of an input in a form.
Here's an example form:
<form> <p> height in feet <input type="number" id="height_feet" name="height_feet"> and <input type="number" id="height_inches" name="height_inches">. <p> <button type="button" id="convert_button">convert to metric</button> <p> <button type="button" id="student_button">student button</button> </form>
You're welcome to click the first button and see how the form works. Later today, you'll define the behavior for the second button.
With a partner, do the following. I expect this exercise to take a while, maybe 20 minutes or more, so don't feel you have to rush.
alert
or console.log
.
Did you get it to work? How far did you get?
Got stuck on step 1
Got stuck on step 2
Got stuck on step 3
Got stuck on step 4 or 5
Got stuck on step 6 -- 9
Complete success!!
A function allows us to package up a chunk of code and give it a name. We can run that code later by invoking (or calling) the function.
We define a function like this:
function name_of_function () { // body of function } function yo () { console.log("Hey there!"); }
We invoke a function using its name and parens:
yo();
Using the JS console, trying invoking yo
. Try defining a
different function called greet
that packages up the code
from question Nr. 2.
The code of a function can be (pretty much) any JS code, so it can get values from a form. Here's an example:
<form> <p>Enter a weight in pounds: <input type="number" id="weight_lbs" name="weight"> <button type="button" id="convert_button2">convert to metric</button> </form>
function convertPounds () { var lbs = parseInt($("#weight_lbs").val()); var kg = lbs / 2.2; alert("In kilos, that is "+kg); }
Using the JS console, fill out the pounds
form and then
invoke convertPounds
.
Then, return to your code from exercise 1 and package it up into a function. Fill out the form and invoke the function.
Another cool thing about functions is that they can be attached to an element in the document, and then the browser can invoke them when an event occurs involving that element. This makes the function an event handler.
We can attach a function to an element using
jQuery's .click()
method. That makes the function
an event handler for events involving the user clicking on
that element.
Here's an example.
Here's the HTML:
<form> <p>weight in kilos: <input type="number" id="weight_kg" name="weight_kg"> height in meters: <input type="number" id="height_meters" name="height_meters"> <button type="button" id="bmi_button">compute BMI</button> </form>
Let's define a function to compute the BMI. Note the use of
parseFloat
instead of parseInt
, to allow
people to enter a height of, say, 1.7 meters. We could also allow
people to enter their weight using floating point as well, but forcing
them to round off to the nearest kilo isn't so bad.
function compute_BMI () { var weight = parseInt($("#weight_kg").val()); var height = parseFloat($("#height_meters").val()); var bmi = weight/(height*height) alert("The BMI is "+bmi); }
Let's attach that function to the button:
$("#bmi_button").click(compute_BMI);
Return to your code from exercise 3 and attach the function to the
student_button
.
The conversion functions we defined today are closely tied to the forms that provide the input. That's okay, but there's a better way.
Later in the course, we'll learn how to define generic functions that do, for example, metric conversions for us, on any data. We'll then be able to use those generic functions to create, say, a form that computes BMI using archaic units, without copy/pasting the conversion code.
Quiz question #1 is C.
Quiz question #2 is B or C.
For exercise 1:
var feet = parseInt($("[name=height_feet]").val()); var inches = parseInt($("[name=height_inches]").val()); var total_inches = 12*feet+inches; alert("total inches:" + total_inches); var cm = 2.54 * total_inches; alert("cm:" + cm); var meters = cm/100; alert("meters:" + meters.toFixed(2));
Quiz question #3 is F.
For exercise 2:
function greet() { var user = prompt("what's your name?"); alert("Greetings, "+user); }
For exercise 3:
function convertHeight () { var feet = parseInt($("[name=height_feet]").val()); var inches = parseInt($("[name=height_inches]").val()); var total_inches = 12*feet+inches; alert("total inches:" + total_inches); var cm = 2.54 * total_inches; alert("cm:" + cm); var meters = cm/100; alert("meters:" + meters.toFixed(2)); }
For exercise 4:
$("#student_button").click(convertHeight);