Check the time of day with JQuery

I have been working on a redesign of my friend Kyle Daigle’s blog (currently under construction). The homepage has a large typographical feature which welcomes visitors to the site.

As we were going back and forth on design iterations, Kyle suggested having a customized welcome message based on the time of day. Time is a pretty easy function to grab in PHP (the language WordPress is built on), but this will always return the time of the server, not the client. Luckily, Javascript offers us the perfect solution.

 

In particular, we used the jQuery framework. The solution is actually pretty simple. jQuery fetches the time on the user’s computer with:

datetoday = new Date();
  timenow = datetoday.getTime();
  datetoday.setTime(timenow);
  thehour = datetoday.getHours();

Specifically, this grabs the hour value of the user’s clock in the 24-hour (military) format.

A simple if statement allowed us to “inject” text using jQuery’s before function.

 if (thehour >= 18)
    $("#homeQuote").before("Good evening.");
  else if (thehour >= 12)
    $("#homeQuote").before("Good afternoon.");
  else if (thehour >= 4)
    $("#homeQuote").before("Good morning.");
  else if (thehour >= 0)
    $("#homeQuote").before("You're up late.");
  else
    $("#homeQuote").before("Hey there.");

The code above checks the value of the user’s hour, then adds a message before any element with an ID of homeQuote. jQuery offers a lot of other options for text manipulation, and it’s also possible to do things like add CSS classes or styles.

The Final Product

  datetoday = new Date();
  timenow = datetoday.getTime();
  datetoday.setTime(timenow);
  thehour = datetoday.getHours();

  if (thehour >= 18)
    $("#homeQuote").before("Good evening.");
  else if (thehour >= 12)
    $("#homeQuote").before("Good afternoon.");
  else if (thehour >= 4)
    $("#homeQuote").before("Good morning.");
  else if (thehour >= 0)
    $("#homeQuote").before("You're up late.");
  else
    $("#homeQuote").before("Hey there.");

Updated Code

This was suggested by reader Ben Atkins as a more efficient way to code this. (By no means am I a jQuery expert, so thanks!)

thehour = new Date().getHours();

var homeQuote = "";
if (thehour >= 18)
  homeQuote = "Good evening.";
else if (thehour >= 12)
  homeQuote = "Good afternoon.";
else if (thehour >= 4)
  homeQuote = "Good morning.";
else if (thehour >= 0)
  homeQuote = "You're up late.";
else
  homeQuote = "Hey there.";
$("#homeQuote").before("Good evening.");
Top of Page