Bob
Bob

Reputation: 157

Randomize images every 2 seconds Javascript

I want to randomize three images every 2 seconds in my webpage.

Currently here is my code

function randomImage() {
  var fileNames = [
    "image1.png",
    "image2.jpg",
    "image3.png"
  ];
  var randomIndex = Math.floor(Math.random() * fileNames.length);
  document.getElementById('#background').innerHTML = 'url(' +
    fileNames[randomIndex] + ')';
}
randomImage();
setInterval(randomImage, 1000);

I think there is a syntax error as nothing is showing up. I've vetted through it a few times but it's taking a very long time as I'm very new to Javascript. Please help, thank you!

Upvotes: 2

Views: 1109

Answers (5)

Ehsan
Ehsan

Reputation: 12959

Try This :

var ele = document.getElementById ('background') ;

var fileNames = [
  "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDAYrQr9qgT2W00EV_CoCahFki3Vw4lSMNt81k9FCSTXoKT8TY2w",
  "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQEnn9dYYZlciBKfaHCw17-dUgRPX3nq5_6-kV1ua-LIsId5g43uA",
  "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSeY54SaYkaOxxyXlu_ng21EMIBZvJjnZBNQAOsIh_0_6Tvu9et"
] ;

function randomImage() {
  var randomIndex = Math.floor(Math.random() * fileNames.length);
  ele.style.backgroundImage = 'url(' + fileNames[randomIndex] + ')' ;
}

randomImage() ;
setInterval(randomImage, 1000) ;
#background { width: 200px; height:150px; }
<p id="background"></p>

Upvotes: 0

zer00ne
zer00ne

Reputation: 43880

.innerHTML parses a string into HTML if you want to change the url of an image's location there are two situations that are common in which that would be applicable:

Using an <img> tag

     <img src="image1.png">
     document.querySelector('img').src = `image${i}.png`;

Using JS Property imageBackground of the Style Attribute

     <figure class='bkg'></figure>
     document.querySelector('.bkg').style.imageBackground = `url(image${i}.png)`;

It might seem like there's a lag but the index is random thus:

2sec image1, 2sec image1, 2sec image1, etc... that's already 6sec of the same index

Random index of a length of 3 the chances of an index being picked consecutively is 33% of the time. Note the console logging the index every 2sec.


This demo switches the actual tag (replace <b> with an <img> or <div>) using the display property of the [style] attribute.

Demo

function randomImage() {
  var images = Array.from( document.querySelectorAll('b'));
  var randomIndex = Math.floor(Math.random() * images.length);
  console.log(randomIndex);
  for (let img of images) {
    img.style.display = '';
  }
  images[randomIndex].style.display = 'block';
}

setInterval(randomImage, 2000);
b {
  display: none;
  font-size: 40vh;
  text-align: center;
}

.as-console-wrapper {
  width: 30%;
  margin-left:70%;
  min-height: 100%
}
<figure class='bkg'>
  <b>🍔</b><b>🍟</b><b>🥛</b>
</figure>

Upvotes: 0

cantuket
cantuket

Reputation: 1592

You need to set the style.backgroundImage property of the target element, not innerHtml. Also when using getElementById DOM query you shouldn’t include the # only the id’s name.

function randomImage() {
  var fileNames = [
      "image1.png",
      "image2.jpg",
      "image3.png"
    ],
    randomIndex = Math.floor(Math.random() * fileNames.length),
    backgroundImage = 'url(' + fileNames[randomIndex] + ')';

  document.getElementById('background').style.backgroundImage = backgroundImage;
}

randomImage();
setInterval(randomImage, 1000);

Upvotes: 1

user10976548
user10976548

Reputation:

I think this should work(NOTE: untested code):

var randomImage = function() {

 var fileNames = [
    "image1.png",
    "image2.jpg",
    "image3.png",
];

var randomIndex = Math.Round(Math.random() * fileNames.length);

//Change myImage to the id of your image. (example: <img id = "myImage" src = "meme.png"></img>)
document.getElementById("myImage").src = filesNames[randomIndex];
};

randomImage();
setInterval(randomImage, 1000);

Upvotes: 2

doğukan
doğukan

Reputation: 27401

Should be

document.getElementById('background').style.background

Upvotes: 2

Related Questions