Time Sensitive Greeting

This is a quick tutorial on how I created the time sensitive greeting you see on the home page of this site. I created this in JavaScript so that it would use the viewers local time and not the server’s time, and if the viewer doesn’t have JavaScript enabled, it falls back to a simple “Hello”.

The code:

<script type="text/javascript">
  function time_sensitive_greeting()
    // Time sensitive greeting message
    // set up greetings
    var morning = "Good Morning";
    var afternoon = "Good Afternoon";
    var evening = "Good Evening";

    // html element (spans are best) that will contain the greeting
    var greet_element = document.getElementById("time_sensitive_greeting");

    // ------- DON't CHANGE ANYTHING BELOW THIS LINE ------- \\

    // get the current time
    var time = new Date();
    var hours = time.getHours();

    if(hours >= 0 && hours < 12) greet_element.innerHTML = morning;
    else if(hours >= 12 && hours < 18) greet_element.innerHTML = afternoon;
    else if(hours >= 18 && hours < 24) greet_element.innerHTML = evening;

  if(window.addEventListener) window.addEventListener('DOMContentLoaded', time_sensitive_greeting, false);
  else if (document.addEventListener) document.addEventListener("DOMContentLoaded", time_sensitive_greeting, false);
  else if(window.attachEvent) window.attachEvent('onload', time_sensitive_greeting);

Simply paste that code into your page, and create an element with the id of “time_sensitive_greeting” on the same page, this script will then replace the content of the “time_sensitive_greeting” element with one of the greeting messages depending on the current time.

- MB

Posted in: Programming by Matt Bearman on 22nd July 2009 at 8:02 am
Tags: , , ,

No Responses to “Time Sensitive Greeting” - (Leave a comment)

No comments yet.

RSS | TrackBack URL

Leave a comment