0

I'm not sure why I can't print the message alongside the current time. The current time only prints when I comment out the if/else/else logic statement. I'm not sure why this is happening

let currentdate = new Date();
let tod = currentdate.getHours();
let dateTime =
  currentdate.getDate() +
  "/" +
  (currentdate.getMonth() + 1) +
  "       " +
  currentdate.getHours() +
  ":" +
  currentdate.getMinutes();

window.onload = function() {
  document.getElementById("time").innerHTML = dateTime;
};

if (tod < 11) {
  message = "Good Morning.";
} else if (tod < 16) {
  message = "Good Afternoon.";
} else {
  message = "Good Evening.";
}
window.onload = function() {
  document.getElementById("tod").innerHTML = message;
};
  • 5
    because `window.onload = function() {` overrides the first one.... either combine them into one or use addEventListener – epascarello Mar 20 '19 at 22:20
  • Possible duplicate of [Add two functions to window.onload](https://stackoverflow.com/questions/16683176/add-two-functions-to-window-onload) – Conspicuous Compiler Mar 20 '19 at 22:22
  • That fixed it! You're brilliant! – Rafael Marrero Mar 20 '19 at 22:22
  • 1
    On a code note, don't use string concatenation (the whole `'..' + '..' + '..'` business). Use template literals so you can just "put the values where they should go" inside your string: ```let c = currentDate, dateTime = `${c.getDate()}/${c.getMonth() + 1} ${c.getHours()}:${c.getMinutes()}`;``` – Mike 'Pomax' Kamermans Mar 20 '19 at 22:22
  • @Mike'Pomax'Kamermans while I couldn't agree more than template literals make things like this vastly nicer, there should be a caveat that this won't work in IE without transpiling. – Robin Zigmond Mar 20 '19 at 22:45
  • only in IE11, which is only available on operating systems where Microsoft tells you to use Edge (if you're a consumer), so in 2019 that shouldn't really be a problem anymore (at least not if you're making normal websites). – Mike 'Pomax' Kamermans Mar 20 '19 at 23:00
  • while I agree that there is no Earthly reason why anyone should still be using IE, it seems that - at least here in the UK - a lot of organisations still do... – Robin Zigmond Mar 20 '19 at 23:59

0 Answers0