heres my code
<style>
body,
html {
height: 100%;
margin: 0;
}
.bgimg {
height: 100%;
background-position: center;
background-size: cover;
position: relative;
color: black;
font: areial;
font-size: 25px;
}
</style>
<div >
<div style="background-image: url(noon.png) ;">
<script>
var img = "background-image: ";
var d = new Date();
var n = d.getHours();
if (n > 20 || n < 6)
img.backgroundImage= "url(midnight.png)";
else if (n > 6 && n < 8)
img.backgroundImage= "url(sunrise.png)";
else if (n > 8 && n < 18)
img.backgroundImage= "url(noon.png)";
else (n > 18 && n < 20)
img.backgroundImage= "url(sunset.png)";
</script>
</div>
</div>
the script above is supposed to get the time then display one of the backgrounds but i cant get it to set the background. i dont get any errors so idk what to do.
CodePudding user response:
You don't need to put the script
tag in the div
. You can put it somewhere in the bottom of the body. You are also getting the div
element incorrectly. The img
variable is just a string.
You just need to get the div
element and then set its background image:
<div >
<!-- give it a class !-->
<div style="background-image: url('noon.png');">
</div>
</div>
<script>
var img = document.querySelector(".imgdiv");
var d = new Date();
var n = d.getHours();
if (n > 20 || n < 6) {
img.style.backgroundImage = "url('midnight.png')";
} else if (n > 6 && n < 8) {
img.style.backgroundImage = "url('sunrise.png')";
} else if (n > 8 && n < 18) {
img.style.backgroundImage = "url('noon.png')";
} else if (n > 18 && n < 20) {
img.style.backgroundImage = "url('sunset.png')";
}
</script>
CodePudding user response:
you must need to add widht
and height
for where you show img.
var img = document.querySelector(".change-background");
var d = new Date();
var n = d.getHours();
console.log(n)
if (n > 20 || n < 6)
img.style.backgroundImage= "url(midnight.png)";
else if (n > 6 && n < 8)
img.style.backgroundImage= "url(sunrise.png)";
else if (n > 8 && n < 18)
img.style.backgroundImage= "url(https://image.shutterstock.com/image-photo/word-link-serious-businessman-hands-600w-180015809.jpg)";
else if (n > 18 && n < 20)
img.style.backgroundImage= "url(sunset.png)";
console.log(img.style.backgroundImage);
body,
html {
height: 100%;
margin: 0;
}
.bgimg {
height: 100%;
background-position: center;
background-size: cover;
position: relative;
color: black;
font: areial;
font-size: 25px;
width: 100%;
}
.change-background {
width: inherit;
height: inherit;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
</style>
</head>
<body>
<div >
<div style="background-image: url('sunrise.png');">
</div>
</div>
<script>
</script>
</body>
</html>
Note: must check your path of noon.png
and others img also