Jeroen
Jeroen

Reputation: 67

Text based on time of day

Hi i got this code to show a different message based on the time of the day but it only shows the message after 0. Does anyone know what i'm doing wrong?

JS

    var today = new Date();
    var time = today.getHours();
    var greet;


    if (time > 0) {
    greet = 'text 1';
    } else if (time > 12) {
    greet = 'Good afternoon Sir!';
    } else if (time > 18) {
    greet = 'Good evening babe!';
    } else {
    greet = 'yo shits broken yo!';
    }


    var show = document.getElementById('message');
    show.textContent = greet;

HTML

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <meta name="description" content="Productiviteits website voor eigen gebruik :) ">
    <meta name="keywords" content="HTML,CSS,JavaScript">
    <meta name="author" content="Jeroen Renema">

    <!-- Title -->

    <title>Productivity Library</title>
    </head>
    <body>
    <h2 id="message">hey</h2>
    <script src="js/Welcome.js"></script>
    </body>
    </html>

Upvotes: 0

Views: 1867

Answers (2)

eisbehr
eisbehr

Reputation: 12452

Think about the order of your if. The first matching condition will be executed. And > 0 will be matched even if the value is > 12 or > 18. So just change the order. ;)

And I would suggest to change the last check to time >= 0, because if someone will access this page just after midnight, the text yo shits broken yo! will be displayed until it's 1 o'clock.

var today = new Date();
var time = today.getHours();
var greet;

if (time > 18) {
  greet = 'Good evening babe!';
} else if (time > 12) {
  greet = 'Good afternoon Sir!';
} else if (time >= 0) {
  greet = 'text 1';
} else {
  greet = 'yo shits broken yo!';
}

var show = document.getElementById('message');
show.textContent = greet;
<h2 id="message">hey</h2>

Upvotes: 2

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

Your comparison should also include the && on the value of the below condition to make it work correctly. Currently time > 0 is always true no matter what the value of time, it just need to be greater than 0 so to make that work, add and condition too.

var today = new Date();
var time = today.getHours();
var greet;


if (time > 0 && time <= 12) {
  greet = 'text 1';
} else if (time > 12 && time <= 18) {
  greet = 'Good afternoon Sir!';
} else if (time > 18 && time <= 24) {
  greet = 'Good evening babe!';
} else {
  greet = 'yo shits broken yo!';
}


var show = document.getElementById('message');
show.textContent = greet;
<h2 id="message">hey</h2>

Upvotes: 1

Related Questions