Introduction to JavaScript
Today, we will practice using variables and some of the
Javascript built-in functions and methods:
prompt()
document.write()
alert()
parseFloat()
We will also try our hand at executing some JavaScript statements.
Task 1: Create an html document named
ask_name.html. Add Javascript statements to do the following:
Click here
to see a demonstration of how your page should work.
Task 2: Part A. Create a new html document named
ask_year.html. Use Javascript to:
- Prompt the user for the year (s)he was born,
- Save this piece of information in a variable,
- Calculate the age of that user in the current year.
- Output the age of the user, using an alert box. For instance, if the
user enters 1986, then the alert box should display something like "I
think you are 21 years old"
Save your work in a file named "partA.html"
Click here
to see a sample page.
Part B. You probably noticed that the age
displayed in the alert box is not correct for those whose birthday hasn't
come yet this year: for example, if your birthday is in January 1986, then
you are already 21. However, those born in November are still 20.
Change the message produced so that now it displays both possiblities:
"I think you are 20 or 21 years old".
This time, use a document.write() statement, instead of an alert(),
to add the message to the page itself.
Save your work in a file named "partB.html"
Click here
to see a sample page.
Part C.
You know already that it is possible to produce any HTML tag from within Javascript.
To make your dynamically produced page in part B more appealing, try to insert an image
on it.
Some useful points:
- It is a good idea to start by saving the file from part B with a different name (such as
partC.html), so that you don't have to re-type all the code.
- Of course, it is possible to place the image on the page using plain old HTML.
However, just for practice, try to produce the IMG tag using Javascript.
- As a reminder, if you are using a relative URL to reference the image file,
make sure you upload both the image file and the html file to view the page from the server.
Click here
to see a sample page.
Task 3:
Here is a sequence of Javascript statements:
var x = prompt("Give me a number.");
var y;
x = x + 2;
y = x;
alert ("The value of x is " + x);
x = 2 * x;
alert("The new value of x is now " + x);
x = x+1;
alert("x is now " + x);
y = x;
alert("y divided by 3 is: " + y/3);
y = (y -1) % 3;
alert("y is " + y);
Hand-execute this piece of code. Make a note of the results you expect.
Then, write a Javascript program using these statements, to verify your predictions.
Have fun with JavaScript!
Introduction | Syllabus | Assignments | Documentation | Project
|