Error while changing Javascript image

Asked

Viewed 45 times

0

Image is not changing depending on time:

function charge() {
  var msg = window.document.getElementById('msg')
  var img = window.document.getElementById('photo')

  var date = new Date()
  var hour = date.getHours()
  var minutes = date.getMinutes()

  msg.innerHTML = `Agora são ${hour} horas e ${minutes} minutos`
  if (hour >= 0 && hour < 12) {
    img.src = 'manha.png'
  } else if (hour >= 12 && hour < 18) {
    img.src = 'tarde.png'
  } else {
    img.src = 'noite.png'
    console.log(hour)
  }
}

1 answer

1


Well, there are some considerations to be made about your code:

HTML

<div id = 'msg'></div>
<br />
<img id = 'photo' />

Here in javascript you declared the function, but forgot to call it, which in this case was only charge();.

JAVASCRIPT

function charge() {
  var img = window.document.getElementById('photo');
  var msg = window.document.getElementById('msg');

  var date = new Date();
  var hour = date.getHours();
  var minutes = date.getMinutes();

  msg.innerHTML = `Agora são ${hour} horas e ${minutes} minutos`
  if (hour < 12) {
    img.src = 'https://meuprimeiroape.blog.br/wp-content/uploads/2017/04/sol-manha.jpg';
  } else if (hour <= 18) {
    img.src = 'https://cdn.mensagenscomamor.com/content/images/p000007513.jpg?v=0';
  } else {
    img.src = 'https://www.eusemfronteiras.com.br/wp-content/uploads/2018/09/Capturar.png';
  }
}

charge();

As indicated by Augusto Vasques, also has unnecessary comparisons, and the first condition hour < 12 if not correct, already eliminates the possibility of being morning, the second condition checks if it is afternoon, being hour <= 18 no longer being redundant the option of morning in comparison and finally, if not satisfying these conditions, ends as night.

See the code working:

https://jsfiddle.net/2reugtxj/

  • 1

    I agree with you, I will change my answer. Thank you very much.

Browser other questions tagged

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