Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding array result to a string

This is a little script randomizing what picture should it display. I can easily set this to an <img> using document.getElementById("pic").src = randPics[randNumGen], but the background tag requires me to use url(). How can I set document.body.style.background to "url(and the random image here)"? Please no JS libraries.

const randPics = ["https://i.ibb.co/6JBbMYm/pic1.jpg", "https://i.ibb.co/rHjTdfc/pic2.jpg"];

window.onload = choosePicture();

function choosePicture() {
  let randNumGen = Math.floor(Math.random() * randPics.length);
  console.log(randNumGen);
  document.body.style.background = "randPics[randNumGen]";
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="styles.css">
  <script async src="index.js" type="text/javascript"></script>
</head>

<body>
  <img width="500px" src="#" alt="pic" id="pic">
</body>

</html>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var url = randPics[randNumGen];

document.body.style.backgroundImage = "url('"+ url + "')";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading