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/
This answers your question? Store an image within a javascript variable?
– Augusto Vasques
No, because it’s more pictures.
– Lucas