//Javascript code to change background color according to day/night.
//We can change background image instead of color as well.
<html>
<head>
<script>
function dayandnight(){
var current = new Date();
var day_night = current.getHours();
if (day_night < 12){
//Day
var bodyColor = document.getElementsByTagName("BODY")[0];
bodyColor.style.backgroundColor = "blue";
document.write("Day");
}
else{
//Night
var bodyColor = document.getElementsByTagName("BODY")[0];
bodyColor.style.backgroundColor = "red";
document.write("Night");
}
}
</script>
</head>
<body>
<script type="text/javascript">
dayandnight();
</script>
</body>
</html>
//We can change background image instead of color as well.
<html>
<head>
<script>
function dayandnight(){
var current = new Date();
var day_night = current.getHours();
if (day_night < 12){
//Day
var bodyColor = document.getElementsByTagName("BODY")[0];
bodyColor.style.backgroundColor = "blue";
document.write("Day");
}
else{
//Night
var bodyColor = document.getElementsByTagName("BODY")[0];
bodyColor.style.backgroundColor = "red";
document.write("Night");
}
}
</script>
</head>
<body>
<script type="text/javascript">
dayandnight();
</script>
</body>
</html>
can you help me to change the background image instead of colors according to day and night my friend ?
ReplyDeleteHi. PFA the portion of the code you need to change
ReplyDeletebodyColor.style.backgroundImage = "url('https://www.w3schools.com/css/img_fjords.jpg')";