3
  • 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>

3
  • What do you exactly mean by ' want more background images ' ? Commented May 4, 2022 at 14:25
  • Add more url to the array? Commented May 4, 2022 at 14:27
  • The background-image property you set is not correct, it will be ' + selectBG + ' instead of the url. Try $('body').css({"background-image":"url('" + selectBG + "')"}); (additional double quotes). Commented May 4, 2022 at 14:36

4 Answers 4

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for pointing my errors, your solution worked for me.
0

There are a three critical problems with your code.

#1 - You have not imported jQuery

If you looked in your console, you could easily see that you get the $ is not defined error. This would give you the conclusion that you don't even have jQuery imported in your HTML.

Solution: The easiest way to import jQuery is through their cdn. Add the script tag before your other script tags.

#2 - Your array does not contain raw pictures

You're linking "https://github.com/NisooJadhav/clock/blob/main/6.jpg" for example, but it should be "https://github.com/NisooJadhav/clock/blob/main/6.jpg?raw=true". Notice ?raw=true at the end to link to the raw picture, otherwise you're just linking to a webpage of github.

#3 - Template literal not correct

Your template literal at "url(' + selectBG + ')" is not correct at all, this is not how JS works. Please see the mdn docs on Template literals and educate yourself!

Conclusion

You're just working in a messy way, without proper debugging. In the future, when coding, try going over everything step by step. Don't just do everything at once, because you'll get confused and end up with very frustrating code.

Also make sure you understand everything you're doing, otherwise you'll end up in a mess. If you don't understand what you're doing, or you don't understand how a certain aspect of JS works, then go look at docs/tutorials such as MDN or YouTube Good luck!

Comments

0

The background features are not working mainly because of two things. The URLs your working with are not correct. For intance:

<img src='https://github.com/NisooJadhav/clock/blob/main/1.jpg' />

It should be:

<img src='https://raw.githubusercontent.com/NisooJadhav/clock/main/1.jpg' />

The other problem is in this line $('body').css({"background-image":"url(' + selectBG + ')"});

Look how it console logs:

let selectBG = 'random string'

console.log("url(' + selectBG + ')")

I changed it like so:

let selectBG = 'random string'

console.log(`url(${selectBG})`)

The fixed 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-image: url('https://raw.githubusercontent.com/NisooJadhav/clock/main/7.jpg');
  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()
      document.getElementById("h").innerHTML = h + " : " + m + " : " + s;
      setInterval("load()", 1000);
    }
  </script>

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

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

</html>

Comments

0

Maybe you mean something like that?

https://codepen.io/steru92/pen/xxYGLea

// array with urls
let imagesUrls = [
    url1, url2, ...
]

// function get random integer between two passed input
function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

// get random integer passing values for array length bounds
const rndInteger = getRndInteger(0, imagesUrls.length - 1);

// get random image
const rndImage = imagesUrls[rndInteger];

// set body background with random image
document.body.style.backgroundImage = 'url("' + rndImage + '")';

1 Comment

Yeah, I understood the logic of setting background-images randomly. Thanks for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.