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

Time:05-04

  • 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 onl oad="load()">
  <div>
    <p id="h"></p>
  </div>
</body>

</html>

CodePudding user response:

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 onl oad="load()">
  <div>
    <p id="h"></p>
  </div>
</body>

</html>

CodePudding user response:

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!

  • Related