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
Our HTML
for today couldn't be easier, we can leverage just one div.
<div id="greeting"></div>
Inside this div, we will place whatever greeting is valid for that time.
Styling our page
Let's also add some basic styling to our page, nothing crazy, just a quite big centered block.
body {
display: grid;
place-items: center;
min-height: 100vh;
font-family: Roboto, 'Helvetica Neue', Arial, sans-serif;
background: #ffe6ab;
}
div {
padding: 2rem;
background: #06d6a0;
border-radius: 10px;
font-size: 3rem;
color: #fff;
}
The center method used is the Grid absolute center.
Vanilla JavaScript time bases greeting
On to the JavaScript part, for this, we need to first get the greeting div.
We use the documentGetElementById
selector.
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 getHours
method.
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[0];
else if (hour < 18) welcomeText = welcomeTypes[1];
else welcomeText = welcomeTypes[2];
If the hour is below 12 we return welcomeType[0]
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.
Thank you for reading, and let's connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter