1

here's my code for the random colors

const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];

const btn = document.getElementById('btn');
const color = document.querySelector('.color');

btn.addEventListener('click', function () {
  console.log(document.body);
  //get random number between 0 - 3
  const randomNumber = getRandomNumber();
  console.log(randomNumber);

   document.body.style.backgroundColor = colors[randomNumber];
   color.textContent = colors[randomNumber]
});

function getRandomNumber() {
   return Math.floor(Math.random() * colors.length);
}

can somebody please tell me how to do the same thing but with picture;

Jared Smith
  • 19,721
  • 5
  • 45
  • 83

2 Answers2

0

You can do something like this

const picture = ["http://jsfiddle.net/img/logo.png", 
"http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=3c6263c3453b", ];

const btn = document.getElementById('btn');
const color = document.querySelector('.color');

btn.addEventListener('click', function () {  
console.log(document.body);
const randomNumber = getRandomNumber();
console.log(randomNumber);

document.body.style.background = url(picture[randomNumber])
});

function getRandomNumber() {
return Math.floor(Math.random() * picture.length);
}
0

const picture = ["https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2019/08/google-play-store-apps-malware-796x450.jpg", 
"https://images.assettype.com/swarajya%2F2018-12%2F488c80cd-37d3-4c8a-876e-144f076e3392%2FGettyImages_631066318.jpg?w=640&q=75&auto=format%2Ccompress", "https://images.idgesg.net/images/article/2020/04/chrome-os-plan-100838340-large.jpg" ];

const btn = document.getElementById('btn');
// const color = document.querySelector('.color');

btn.addEventListener('click', () => {  
    const randomNumber = getRandomNumber();
    document.body.style.background = `lightblue url(${picture[randomNumber]}) no-repeat fixed center`;
});

function getRandomNumber() {
   return Math.floor(Math.random() * picture.length);
}
<button id="btn">change image</button>
micronyks
  • 54,797
  • 15
  • 112
  • 146