JavaScript Conditionals

In today's lab we will get practice with Javascript conditionals and with the Date built-in object. Here is a quick reference to the Date object.

Exercise 1. Fortune-telling page

  • Create a new HTML document and save it, on your Desktop, as fortune.html.
  • You will add some JavaScript code to it, so that the text on the page is dependent upon the computer's time. If the page loads when the seconds are less than 30, then your page will contain an optimistic fortune (e.g. Today is your lucky day). If the page loads when the seconds are greater than 30, the page will contain a pessimistic fortune (e.g. You will have much pain and suffering today).
  • For this exercise you will need to use the Date object, and some of its methods, as well as the document.write() built-in Javascript method. In addition, you will use the conditional statement (if - else).
  • To check that your program works correctly, display the current seconds on the page itself.
  • For further practice with Javascript conditionals, display the minutes in a 2-digit format like this :09 seconds

Here is a demo of the page.

Exercise 2. Your Wellesley class color

Create a new html document, and save it as color.html on your Desktop. Write some Javascript to ask the user for Wellesley year of graduation and save the year in a variable. Change the background color of your page to reflect the class' color, using the table below:

2008 red
2009 green
2010 purple
2011 yellow

Hint: You can change the document's background color in JavaScript like this:
document.bgColor = 'red'

  • Test your code with inputs in all the years above, to make sure it works correctly.
  • Add some text indicating the student's year (e.g. Go Junior Class!) to the page.
  • If the user types in a year not in the range 2008-2011, then have an alert box come up with a warning, and ask the user to reload the page to rerun the program.

You can also set the year from within your JavaScript code, for testing purposes. Experiment with this way as well, as it will be useful experience for your current homework assignment. Here is a demo of the Class Color page.

More Conditionals, and Strings

If you have more time, start working on this problem.

Have fun with JavaScript!


Introduction | Syllabus | Assignments | Documentation | Project