<div id="background">
<h1 id="greeting"></h1>
</div>
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display&display=swap');
body {
margin: 0;
}
#background {
height: 100vh;
background-size: cover;
background-position: center;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
#background::before {
content: '';
width: 100%;
top: 0;
height: 100%;
left: 0;
position: absolute;
background-color: rgba(0, 0, 0, 0.1);
}
#greeting {
color: white;
position: relative;
font-family: 'Playfair Display', serif;
padding: 16px;
}
const backgrounds = [
{
min: 0,
max: 6,
src: "https://assets.codepen.io/210284/night_-__Night_sky_watercolor_background.jpg",
greeting: "Quiet Hours 😴"
},
{
min: 6,
max: 12,
src: "https://assets.codepen.io/210284/evening_-_River_Landscape_at_Sunset.jpg",
greeting: "It's going to be a beautiful day 😊"
},
{
min: 12,
max: 17,
src: "https://assets.codepen.io/210284/morning_-_Mountain_Morning_-_Illustration_Background.jpg",
greeting: "Good afternoon"
},
{
min: 17,
max: 21,
src: "https://assets.codepen.io/210284/sunset_-_Black_Castle_in_the_Sunset.jpg",
greeting: "Good evening"
},
{
min: 21,
max: 24,
src: "https://assets.codepen.io/210284/night_-_Mountains_in_the_Night.jpg",
greeting: "Good night"
}
];
const backgroundEl = document.getElementById("background");
const greetingEl = document.getElementById("greeting");
const getCurrentHour = () => {
const currentDate = new Date();
return currentDate.getHours();
};
const setBackground = () => {
const currentHour = getCurrentHour();
const currentBackground = backgrounds.find((background) =>
background.min <= currentHour && background.max > currentHour
);
backgroundEl.style.backgroundImage = `url(${currentBackground.src})`;
greetingEl.innerHTML = currentBackground.greeting;
};
window.addEventListener("load", () => {
setBackground();
const everyHour = 1000 * 60 * 60;
setInterval(setBackground, everyHour);
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.