Lab: Javascript User Defined Functions
Goals
The goal of this lab is to practice your JS skills. Specifically, you will get practice with:
- variables and conditional statements
- reading from input elements on the web page
- writing on the web page from text input elements
- defining functions with and without input arguments
- adding of a responsive button on a web page
-
use the click event on a button to trigger the call of a function
Some reminders and background
-
Here is how you can add an
input box
on a web page, to ask for the user's first name:Please enter your first name: <input type="text" id="firstNameId"></input>
-
To read the value from the text input above:
document.getElementById("firstNameId").value;
The value from a text input is read as a String, and therefore it may need to be parsed into a number some times.
- Here is how you can add a
responsive button
on a web page:<input type="button" value="Click Me!" onClick = "reactToTheClick();">
In the tag above, the
reactToTheClick()
is considered to be a javascript function that defines the reaction to the user clicking on the button.
Task 0: Starting material
Please download lab09
folder from the download directory.
Task 1: Time Elapsed
Write a function to report, in the timeElapsed.html
web page, the number of
minutes that have passed since the start of the current day.
Your code should display a message that looks like
this when the "Find the Age of this day" button is clicked:
This day is 860 minutes old.
What should be the name of the .js file to contain the function definition? What exactly should be the name of the function?
Where should you look to figure the answers to the above questions?
Task 2: Voting or Not?
Open the provided voting.html
file and read the html code there. Make sure you are familiar with the different elements in there.
Answer the following questions:
-- How can you get the user's birth year into your js program?
--How will you write the results of the program in the appropriate area?
--How would the calculations be triggered?
In the appropriate js document, provide the definition of two functions:
One named decideVotingEligibility()
to do exactly that:
returns true if a user is eligible to vote, false otherwise.
Eligibility is determined based on age only: if the age is at least 18, the answer is positive.
The function takes as input the year of the user's birth.
The second function is named processAndPrintResults()
.
It reads from the web page the year entered by the user, and calls the decideVotingEligibility()
. Finally, it prints an informative message on the page.