I think this is what you want...
In the following code an object is defined backgroundUrlsPerHour
where each key represents an hour and its value is the url of an image. You can add more entries to this object (one per hour) if you want to.
The function runBackgroundRotator
checks every 15 minutes (default value that can be changed when calling the function) the current time and changes the background image whenever necessary.
I also implemented the function setInitialBackground
who is responsible for setting the background image when starting the application. Basically checks "what time of day we are" and sets the corresponding image.
const backgroundUrlsPerHour = {
7: 'https://via.placeholder.com/1024/ADD8E6/FFFFFF/?text=manh%C3%A3',
12: 'https://via.placeholder.com/1024/FFC475/FFFFFF/?text=tarde',
19: 'https://via.placeholder.com/1024/333333/ffffff/?text=noite',
};
const setInitialBackground = () => {
const hour = (new Date).getHours();
if (backgroundUrlsPerHour[hour]) {
switchBackground(backgroundUrlsPerHour[hour]);
return;
}
const sortedHours = Object.keys(backgroundUrlsPerHour).sort(
(a, b) => a - b,
);
let closestHour = sortedHours.reduce((acc, cur) =>
Math.abs(cur - hour) < Math.abs(acc - hour) ? cur : acc,
);
if (closestHour > hour) {
const closestHourIndex = sortedHours.indexOf(closestHour);
closestHour = closestHourIndex === 0
? sortedHours[sortedHours.length - 1]
: sortedHours[closestHourIndex - 1];
}
switchBackground(backgroundUrlsPerHour[closestHour]);
};
const runBackgroundRotator = (checkInterval = 900000) => {
const bodyElement = document.querySelector('body');
setInterval(() => {
const hour = (new Date).getHours();
if (backgroundUrlsPerHour[hour]) {
switchBackground(backgroundUrlsPerHour[hour]);
}
}, checkInterval);
};
const switchBackground = (backgroundUrl) => {
const bodyElement = document.querySelector('body');
const currenBackgroundImage = bodyElement.style.backgroundImage;
const newBackgroundImage = `url('${backgroundUrl}')`;
if (newBackgroundImage !== currenBackgroundImage) {
bodyElement.style.backgroundImage = `url('${backgroundUrl}')`;
}
};
setInitialBackground();
runBackgroundRotator();
body {
background-repeat: no-repeat;
background-size: cover;
}
right, but I wanted to add at the bottom of the page. the "id = photo" and only a div.
– walace js
@walacejs test the change
– Zé Reis M. Olliver
Show worked out my muuuuuuuuuito thanks for the attention.
– walace js