Greet your Visitors with Good Morning, Good Afternoon or Good Evening Message using JavaScript

← PrevNext →

We have seen websites greeting their visitors with a message that says Good morning, good afternoon or good evening, depending upon the time they visit the website. In fact, these are simple client scripts, which read the active visitors computer’s time. Here, in this article, I’ll show you how to greet your website visitors with a message. This article and the examples are for beginners.

As little kids, we were taught how to greet our guests, family and friends depending upon the time of the day. I need not repeat it here, because you all are grown up now. However, we need to make our web page understand these courtesies and greet ours visitors accordingly.

Note: I have seen scripts written using Asp.Net and other server side languages, to do the same. However, be advised that the server time may not co-inside with the clients computer time. Therefore, it advisable not to use a server side script. Instead, use a client side script for accuracy.

The Markup

In our markup section, we have added a <label> to display the message. However, you may also use document.write() method for the same.

    <title>Greeting Message using JavaScript</title> 
    <label id="lblGreetings"></label>

    var myDate = new Date();
    var hrs = myDate.getHours();

    var greet;

    if (hrs < 12)
        greet = 'Good Morning';
    else if (hrs >= 12 && hrs <= 17)
        greet = 'Good Afternoon';
    else if (hrs >= 17 && hrs <= 24)
        greet = 'Good Evening';

    document.getElementById('lblGreetings').innerHTML =
        '<b>' + greet + '</b> and welcome to Encodedna.com!';
Try it


The JavaScript Date() method will return the current date and time of your user’s computer. The method offers many set and get methods. Out of many get methods, we will use the getHours() method, which will return hours between 0 and 23.

← PreviousNext →