How to set images of background html body using JS Array containing url of images?

Issue

  • I am creating Digital Clock page. I want to set background of body to
    various images randomly as we refresh the page, or visit it again.
  • I have JavaScript array containing array elements of url/local files.
  • I tried using jQuery to set background, but something is broken.
    https://codepen.io/nisoojadhav/full/oNEXWdg
  • This is working but I want more background-images.

Below is my code:

<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">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Bungee&display=swap" rel="stylesheet">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <title>Clock</title>
  <style>
p {
  font-family: 'Bungee', cursive;
  font-size: 100px;
  color: white;
  text-shadow: 2px 3px 2px rgb(0, 0, 0);
  padding-top: 0px;
  padding: center;
}
div{
  vertical-align: center;
  text-align: center;
}   
body {
  background: url(https://github.com/NisooJadhav/clock/blob/main/5.jpg?raw=true);
  background-size: 100%;
}

@media screen and (max-width:650px) {
  p {
    font-size: 60px;
    line-height:0;

  }

  body {
    background-size: 300%;
  }
}
  </style>

  <script>
    function load() {
      var d = new Date
      var h = d.getHours()
      var m = d.getMinutes()
      var s = d.getSeconds()
      //alert(h+":"+m+":"+s)
      document.getElementById("h").innerHTML = h + " : " + m + " : " + s;
      setInterval("load()", 1000);
    }
  </script>

  <script>
        var bgImg = ['https://github.com/NisooJadhav/clock/blob/main/1.jpg','https://github.com/NisooJadhav/clock/blob/main/2.jpg','https://github.com/NisooJadhav/clock/blob/main/3.jpg','https://github.com/NisooJadhav/clock/blob/main/4.jpg','https://github.com/NisooJadhav/clock/blob/main/5.jpg','https://github.com/NisooJadhav/clock/blob/main/6.jpg','https://github.com/NisooJadhav/clock/blob/main/7.jpg']
        var selectBG = bgImg[Math.floor(Math.random() * bgImg.length)];
        //var r = Math.floor(Math.random() * 10)
        $(document).ready(function()
        {
            $('body').css({"background-image":"url(' + selectBG + ')"});
        });
  </script>
</head>

<body onload="load()">
  <div>
    <p id="h"></p>
  </div>
</body>

</html>

Solution

Problems

  1. The array of image urls point no where (404).
  2. The clock() function (originally load()) freezes after a couple seconds.
  3. The text shifts left and right when hours, minutes, and seconds go to or from single and double digits.
  4. Some CSS values are wrong
    • vertical-align: center
    • padding: center
    • line-height: 0
  5. Although not problem, 99% of <script> tags should be placed before the closing </body> tag.

Solutions

  1. Added an array of urls that point to images. Made a function bgSwitch() that generates a random number in the range of 0 to array.length -1 (remember an array is 0 based index), and assigns the background-image to <body>.

  2. Moved setInterval() outside of clock() function and corrected the first parameter:

    setInterval(clock, 1000)
    
  3. Changed the font of the HMS to a monospace type and zero padded HMS with .toString().padStart(); now the clock doesn’t shift.

  4. Removed all incorrect CSS because even if they had correct values it would be ineffective or detrimental to the styles because they’re on the wrong selector. Also, the CSS and HTML was slightly altered for centering, aesthetics, responsiveness, and semantics.

  5. Also removed the onload event handler on <body> it’s not needed. By simply placing <script> tags to the location mentioned in Problems #5, you can call functions like you normally do.

PLUNKER

<!DOCTYPE html>
<html>
  <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>Clock</title>
    <style>
      @import url('https://fonts.googleapis.com/css2?family=Bungee&family=Noto+Sans+Mono:wght@600&display=swap');

      html {
        font: 2vmax/1 'Noto Sans Mono';
      }

      body {
        background: url(https://github.com/NisooJadhav/clock/blob/main/5.jpg?raw=true);
        background-size: 100%;
        overflow: hidden;
      }

      main {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100vw;
        min-height: 100vh;
        margin: 0 auto;
      }

      time {
        display: inline-block;
        width: 50vw;
        height: 20vh;
        font-size: 4rem;
        line-height: 2;
        color: white;
        text-shadow: 2px 3px 2px rgb(0, 0, 0);
        text-align: center;
      }

      @media screen and (max-width: 650px) {
        html {
          font-size: 3vmax;
        }
        time {
          width: 90vw;
          font-size: 4rem;
        }
        body {
          background-size: cover;
        }
      }
    </style>
  </head>

  <body>
    <main>
      <time></time>
    </main>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      const bgImg = [
        'https://github.com/NisooJadhav/clock/blob/main/5.jpg?raw=true/',
        'https://i.ibb.co/0m6612N/static.gif',
        'https://i.ibb.co/2cNgPHW/matrix.jpg',
        'https://i.ibb.co/LdQzP9j/wall1.jpg',
        'https://i.ibb.co/pKPKR1v/wall0.jpg',
      ];

      function clock() {
        const d = new Date();
        let h = d.getHours().toString().padStart(2, '0');
        let m = d.getMinutes().toString().padStart(2, '0');
        let s = d.getSeconds().toString().padStart(2, '0');
        document.querySelector('time').innerHTML = h + ':' + m + ':' + s;
      }

      function bgSwitch(array) {
        const randomRng =
          Math.floor(Math.random() * (array.length - 1 - 0 + 1)) + 0;
        let current = bgImg[randomRng];
        document.body.style.cssText = `background: url(${current})`;
      }

      bgSwitch(bgImg);
      setInterval(clock, 1000);
    </script>
  </body>
</html>

Answered By – zer00ne

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.