Display different message according to time

Asked

Viewed 65 times

0

I need help to make it appear, according to the time I opened the page show Good morning, Good afternoon or good night, someone can help me?

function carregar() {
  var msg = document.getElementById("msg")
  var img = document.getElementById("imagem")
  var data = new Date() //aqui é para mostrar a data atual
  var hora = data.getHours() //aqui é para mostrar a hora atual
  var minuto = data.getMinutes() // aqui vai mostrar os minutos

  msg.innerHTML = 'Agora são ' + hora + " : " + minuto + ' horas.'
  if (hora >= 0 && hora < 12) {
    //Bom dia !
    img.src = "imagens/fotomanha.png"
    document.body.style.background = "#fee389" // aqui vai mudar a cor de fundo conforme o hrario do dia


  } else if (hora >= 12 && hora < 18) {
    //Boa tarde !
    img.src = "imagens/fototarde.png"
    document.body.style.background = "#bc6317" // aqui vai mudar a cor de fundo conforme o hrario do dia

  } else {
    //Boa Noite !
    img.src = "imagens/fotonoite.png"
    document.body.style.background = "#0b191a" // aqui vai mudar a cor de fundo conforme o hrario do dia
  }

}
  • apparently your code is right. You are calling the function?

1 answer

0


Your question was very little specific, where do you want it to display? In the msg element? An Alert? If it is in the message you can do so:

if (hora >= 0 && hora < 12) {
    msg.innerHTML += ' Bom Dia!'
    img.src = "imagens/fotomanha.png"
    document.body.style.background = "#fee389" 
  } else if (hora >= 12 && hora < 18) {
    msg.innerHTML += ' Boa Tarde!'
    img.src = "imagens/fototarde.png"
    document.body.style.background = "#bc6317" 

  } else {
    msg.innerHTML += ' Boa Noite!'
    img.src = "imagens/fotonoite.png"
    document.body.style.background = "#0b191a" 
  }

With this '+=' you concatenate the value that already exists in innerHTML plus the message that can be good morning, good afternoon or good night.

  • Thank you, that’s just the way I wanted it.

  • You are welcome. Do not forget to accept my answer, that it helps a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.