Java Script Lesson 10 ‘ Conditional Statements
You may have already seen some conditional statements in our last tutorial on how to create your own JavaScript slideshow. Now, we will go more into depth on conditional statements in JavaScript and how you can use them on your web site.
We use a couple examples to illustrate how conditional statements are useful in creating interactive content for your pages. Our first example covers a simple greeting message. Instead of displaying the same greeting throughout the day, this JavaScript will utilize a conditional statement to change the greeting based on the time of the day and your viewer’s browser.
So, let’s get started:

First, we start with the Date tag, which we covered in a previous tutorial. JavaScript has a built in date function that we will be accessing in this script. In addition to the simple date function, we are adding the getHours function. This will enable your script to read the time of your viewer’s browser.
Now, we add our conditional statements. In this script, if the time of your viewer’s browser is less than 10, a message will display on your page that reads Good Morning! This is the IF statement. We now move on to the ELSE statement. If your viewer’s browser time is greater than 10, a message will display that reads Good Afternoon!
This is a very simple illustration of how to customize a greeting for your viewers. You can add different variables, by tightening the amount of time. For example, instead of using greater than 10 to return Good Afternoon, you could state that if the time is less than 15 to return Good Afternoon, and if the time is greater than 15 to return Good Evening.
You can do this by adding another conditional statement after the existing ELSE statement and before the closing tag. Of course, you would need to modify the variables in the ELSE tag above in order for the script to return the correct message.
Feel free to copy and paste this script into your own page and change the variables as needed.
Related Posts:Posted on 12/27/05 2:03 AM
Be the first to comment!