Monday 2 November 2015

Source code to change background color according to Day/Night

//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>

2 comments:

  1. can you help me to change the background image instead of colors according to day and night my friend ?

    ReplyDelete
  2. Hi. PFA the portion of the code you need to change

    bodyColor.style.backgroundImage = "url('https://www.w3schools.com/css/img_fjords.jpg')";

    ReplyDelete