Last Time
We learned about JavaScript functions. They can be defined two ways.
function functionName(arg1, arg2, arg3, .... )
{
//code
}
functionName = function(arg1, arg2, arg3, .... )
{
//code
}
Here we see two functions being created. Notice how one calls the other.
function square(x)
{
let y = x*x;
return y;
}
function cube(t)
{
return t*square(t);
}
a = 5;
console.log(`The cube of ${a} is ${cube(a)}`);
We learned that varables made inside of functions
are invisible outside of them if we use the let
keyword. Also, function paramaters are invisible outside of
their function. We can safely change out program to
look like this.
function square(x)
{
let y = x*x;
return y;
}
function cube(x)
{
return x*square(x);
}
x = 5;
console.log(`The cube of ${x} is ${cube(x)}`);
I primarily use the name x
for mathematical
functions. You can give parameters names evocative of their
purpose.
Functions are useful because they allows us to put complexit in a wrapper and just focus on what the function does, not how it does it.
Arguments vs. Parameters Sometimes these are used synonomously; however, they are not.
Conditional Logic
alert This function accepts a string as an argument, and when called, creates a popup containing that string. Here is usage.
alert("This test will appear in a popup.");
confirm This accepts a string as an argument, which is displayed in a popup. The user can hit OK or cancel. Here is usage.
let reply = confirm("Do you want to do this?");
It returns true
or false
.
prompt This accepts a string as an argument, which is displayed in a popup. It returns the string the user types into the prompt box. Here is usage.
let input = prompt("What is your name?");
Inline JavaScript
You will see this in OPC. Yep, it's ugly and it's ubiquitous.
Here is a typical example.
<!doctype html>
<!--Author: Morrison-->
<html>
<head>
<title>popups</title>
<link rel="stylesheet" href="popups.css"/>
<script src="popups.js">
</script>
</head>
<body>
<h2>Popup Demonstration</h2>
<p>Notice this. If you use one type of quote outside
of a string, the other type becomes an ordinary characters
inside of that string. This is demonstrated here. </p>
<p>This is not the preferred way of doing things but you will
see it in OPC. </p>
<p>We will learn how to separate JS, CSS and HTML and we will try
to keep that separation as strict as possible.</p>
<p><button onclick="alert('You are alerted!');">Alert me!</button></p>
<p><button onclick="confirm('Do you wanna?');">Make a choice!</button></p>
<p><button onclick="prompt('How much is that doggie in the window?');">Make an offer!</button></p>
<p><button onclick="let age = prompt('Enter your age:'); age=Number(age); if(age < 21){console.log('go away')};">Tell your age!</button></p>
</body>
</html>
Look at the code for the three buttons. The first two have a certain degree of odiousness because they used the ' inside of " hack.
Look at the third one. UGH! We have all manner of code crammed
into an onclick
attribute. The JavaScript inside of
an onclick
's value is executed when the element,
in this case, the button, is clicked.
This is ugly and it's not the way we will do JavaScript.
We will strive for a strict separation of JS, HTML and CSS.
To set up for this, place this code in your js
file.
window.addEventListener("load", main);
function main()
{
}
What is all of this? The window
object can be though of as the tab for your browsing session.
The line
window.addEventListener("load", main);
says, "when the page is finished loadiing, call the function
main
.
When the page loads, the browser broadcasts the fact that the page
has loaded to your application. By typing this line, we are making
the window listen for when the page is loaded. Once that occurs,
the function main
is called.
You might ask, "Why do this?" Here are reasons.
Web pages load from top to bottom. Your script loads the head
of the document before any of the body is loaded. IF the script
being invoked in the head of your document has a
document.getElementById
call in it, you wil get an error,
because no page elements exist yet.
What we are doing here is delaying those processes until the page has loaded and the elements can be found.
Simplifying the HTML
<!doctype html>
<html>
<head>
<title>popups</title>
<link rel="stylesheet" href="better.css"/>
<script src="better.js">
</script>
</head>
<body>
<h2>Popup Demonstration</h2>
<p>Notice this. If you use one type of quote outside
of a string, the other type becomes an ordinary characters
inside of that string. This is demonstrated here. </p>
<p>This is not the preferred way of doing things but you will
see it in OPC. </p>
<p>We will learn how to separate JS, CSS and HTML and we will try
to keep that separation as strict as possible.</p>
<p><button id="alertButton">Alert me!</button></p>
<p><button id="confirmButton">Make a choice!</button></p>
<p><button id = "promptButton">Tell your age!</button></p>
</body>
</html>
No more JS resides on this page. To keep things working, we
give the three butttons id
, which we will handle from the
JS file.
Now we create pointers to the three buttons on the page.
window.addEventListener("load", main);
function main()
{
let alertButton = document.getElementById("alertButton");
let confirmButton = document.getElementById("confirmButton");
let promptButton = document.getElementById("promptButton");
}
Since main
is not called until the page loads,
these three variables will point at page elements that now
exist.
Now let's get the alert to work. This involves two steps. First, we will give the alert button an event listener.
window.addEventListener("load", main);
function main()
{
let alertButton = document.getElementById("alertButton");
alertButton.addEventListener("click", createAlert);
let confirmButton = document.getElementById("confirmButton");
let promptButton = document.getElementById("promptButton");
}
The addEventListener
method for a page node
requires two arguments. The first is a string that describes
the type of event it is listening for, and the second is a function
that is called when that event occurs. Here we are listening
for a click event and callling a yet-written function
createAlert
. Let's add it.
window.addEventListener("load", main);
function createAlert()
{
alert("Alert me!");
}
function main()
{
let alertButton = document.getElementById("alertButton");
alertButton.addEventListener("click", createAlert);
let confirmButton = document.getElementById("confirmButton");
let promptButton = document.getElementById("promptButton");
}
Run this code and see that the button works. Warning
the second argument to addEventListener
requires a
function. This is a super common and super annoying error.
alertButton.addEventListener("click", createAlert());
Those parens will mess up your event listener.
Now we add similar code for the other two buttons.
window.addEventListener("load", main);
function createAlert()
{
alert("Alert me!");
}
function createConfirmBox()
{
confirm("Do you wanna?");
}
function createPromptBox()
{
let age = prompt("Enter your age: ");
age = Number(age);
if(age < 21)
{
console.log("go away");
}
}
function main()
{
let alertButton = document.getElementById("alertButton");
alertButton.addEventListener("click", createAlert);
let confirmButton = document.getElementById("confirmButton");
confirmButton.addEventListener("click", createConfirmBox);
let promptButton = document.getElementById("promptButton");
let age = promptButton.addEventListener("click", createPromptBox);
}
Programming Exercise Add this to your document.
Have it display "Go away!" in the empty paragraph
when the prompt button is pushed and
the age is < 21. Hint Learn about
innerText
and innerHTML
.
Simple if
We used this today. Here
is the usage.
if(predicate)
{
//code
}
If the expression predicate
evauates to true
the code is run. Otherwise it is skipped.
Simple else
Simple else if
Truthiness and Falsiness