Previous Page
Next Page

Customizing a Message for the Time of Day

You can take the technique used in the last example and use it again to customize a message for the user, depending on the time of day. This is often used as a friendly greeting when a user enters a site. Script 13.3 shows how it is done, and Figure 13.3 shows how we were up writing way past our usual bedtime.

Script 13.3. Scripts can be used to check what time of day it is and react appropriately.

window.onload = initDate;

function initDate() {
     var now = new Date();
     var dtString;

     if (now.getHours() < 5) {
        dtString = "What are you doing up so late?";
     }
     else if (now.getHours() < 9) {
        dtString = "Good Morning!";
     }
     else if (now.getHours() < 17) {
        dtString = "No surfing during working hours!";
     }
     else {
        dtString = "Good Evening!";
     }

     document.getElementById("dtField"). innerHTML = dtString;
}

Figure 13.3. It was definitely too late at night when we wrote this.


To customize messages for the time of day:

  • if (now.getHours() < 5) {
      dtString = "What are you doing up so late?";
    

    We begin the new code in this script by starting a conditional test. The getHours() method extracts hours from the now variable and then tests to see if that number is less than 5 (which corresponds to 5 A.M., since numbering in JavaScript starts at midnight).

    If it is before 5 A.M., the script scolds the user by writing this message to the document window, as shown in Figure 13.3.

    The rest of the script repeats the above line, adjusting it for the time of day and writing out a different message. If it is between 5 A.M. and 9 A.M., the script says "Good Morning!"; between 9 A.M. and 5 P.M., it says "No surfing during working hours!"; and after 5 P.M., it says "Good Evening!"


Previous Page
Next Page