In today's article, we will be looking at how to greet our users based on their timezone.
We will check for three different times and greet accordingly.
< 12: Everything before 12 should say Good morning
12-18: Middle of the day should say Good afternoon
> 18: After 6 pm so say Good evening
It's a cool rather small script that just makes that little bit of extra effort for the end-user.
You can see the end result based on your time in this Codepen.
HTML Structure permalink
HTML for today couldn't be easier, we can leverage just one div.
Inside this div, we will place whatever greeting is valid for that time.
Styling our page permalink
Let's also add some basic styling to our page, nothing crazy, just a quite big centered block.
font-family: Roboto, 'Helvetica Neue', Arial, sans-serif;
The center method used is the Grid absolute center.
We use the
const greeting = document.getElementById('greeting');
The next thing we need is the current hour for that user. We can access a new
Date object and use the
That will return something like
11 when the time is
11:55 that cool because that's how our greetings will work.
const hour = new Date().getHours();
We will also need our three greeting types.
const welcomeTypes = ['Good morning', 'Good afternoon', 'Good evening'];
The last part we need is a let to put the text in.
let welcomeText = '';
Then we can check if our hour matches certain cases and return the correct line.
if (hour < 12) welcomeText = welcomeTypes;
else if (hour < 18) welcomeText = welcomeTypes;
else welcomeText = welcomeTypes;
If the hour is below 12 we return
welcomeType which is Good morning. If it's below 18 we return Good afternoon and else we return Good evening.
The final step is to put this welcomeText in our div.
greeting.innerHTML = welcomeText;
That it! We now have a fully functional welcome greeting based on the user's time.