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

193
Vistas
Adding classname to elements forEach loop in javascript not working properly

I'm using the javascript forEach method to loop through images and add classnames to it that animates. Basically I want the images to animate one by one with delays between each iteration but it's adding classNames to the elements all at once therefore they are animating all at the same time. What am I doing wrong? and how to fix it?

const images = document.querySelectorAll(".image");
images.forEach((image) => {
setTimeout(function () {
  image.classList.add("move-image-left");
  console.log(image);
}, 100);
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

images.forEach((image, index) as you can see I have used index and then multiply in time inside of setTimeout function.

  • Here is that code,
images.forEach((image, index) => {
  setTimeout(function() {
    image.classList.add("move-image-left");
  }, index * 1000); // this will wait times of current element index
});

For more information, please go through this answer on StackOverflow.

const images = document.querySelectorAll(".image");
images.forEach((image, index) => {
  setTimeout(function() {
    image.classList.add("move-image-left");
  }, index * 1000);
});
.image {
  display: inilne-block;
  height: 50px;
  width: 100px;
  margin-bottom: 10px;
  object-fit: cover;
  overflow: hidden;
  transition: .5s;
}

.move-image-left {
  transform: translateX(50px);
}
<div class="image">
  <img src="https://images.unsplash.com/photo-1659203540215-bb0044083ff5?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwzfHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60" />
</div>
<div class="image">
  <img src="https://images.unsplash.com/photo-1659203540215-bb0044083ff5?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwzfHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60" />
</div>
<div class="image">
  <img src="https://images.unsplash.com/photo-1659203540215-bb0044083ff5?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwzfHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60" />
</div>

about 4 years ago · Santiago Trujillo 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