Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
Repeat background images of a div

I am trying to change the background images of a div, but somehow it runs once and shows the last image and not iterating.

JS

let wrapper = document.querySelector('.wrapper');
let backImages = ['backimage1.jpg', 'backimage2.jpg', 'backimage3.jpg'];

// First way
setInterval(() => {
  for (let bg in backImages) {
    wrapper.style.background = `url('${backImages[bg]}')`;
  }
}, 3000);

// Second way
let changeBg = () => {
  for (let bg in backImages) {
    wrapper.style.background = `url('${backImages[bg]}')`;
  }
};

setInterval(changeBg, 3000);

How can I make it so that it keep iterating over all images endlessly.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I hope this is what you need:

let wrapper = document.querySelector('.wrapper');
let backImages = ['backimage1.jpg', 'backimage2.jpg', 'backimage3.jpg'];
wrapper.style.background = `url('${backImages[0]}')`;
let startIndex = 0;

setInterval(() => {
  startIndex = startIndex + 1;
  if (startIndex == backImages.length) {
    startIndex = 0;
  }

  wrapper.style.background = `url('${backImages[startIndex]}')`;
}, 3000);
<div class="wrapper"></div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Ah, this is because he function is doing the forloop all at once.

Start function after 3 seconds.
   Do ForLoop
     Change 1
     Change 2
     Change 3
Then Apply.

You'll want to have an iteration outside of that.

let wrapper = document.querySelector('.wrapper');
let backImages = ['backimage1.jpg', 'backimage2.jpg', 'backimage3.jpg'];

//Set a cycle count, and get the max number in your array.
var bgCycleCount = 0;
var bgCycleMax = backImages.length;


setInterval(() => {
    //Apply the BG for the current array position.
    wrapper.style.background = `url('${backImages[bgCycleCount]}')`;
    if(bgCycleCount == bgCycleMax) {
      bgCycleCount = 0; //Reset if you've reached the end
    } else {
      bgCycleCount++; //If not the end, increment the array position
    }
}, 3000);
about 4 years ago · Juan Pablo Isaza Denunciar

0

In both the case you are re starting to run the loop from the beginning.

let wrapper = document.querySelector('.wrapper');
let backImages = ['https://www.thespruce.com/thmb/2fz1zlPNq7cj7QkLAtKdqYrKvs0=/3704x2778/smart/filters:no_upscale()/the-difference-between-trees-and-shrubs-3269804-hero-a4000090f0714f59a8ec6201ad250d90.jpg',

  'https://www.sciencenewsforstudents.org/wp-content/uploads/2020/04/1030_LL_trees-1028x579.png', 'https://m.media-amazon.com/images/I/71WcZqPYToL._SL1200_.jpg'
];
let count = 0;
setInterval(() => {
  wrapper.style.background = `url('${backImages[count]}')`;
  count = count === backImages.length - 1 ? 0 : count + 1;
}, 3000);
.wrapper {
  width: 500px;
  height: 500px;
  border: 1px solid red;
}
<div class='wrapper'></div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda