Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
Multiple vanilla JS carousels running on same script

I want to have two independent image carousels, stacked on top of each other. I thought making both of them with the same class would make them both work from the same script - but only the first one scrolls. Is it because of the array variable?

window.onload = function(){
    var track = document.querySelector('.carousel_track');
    var slides = Array.from(track.children);

function setSlidePosition (slide, index) {
    slide.style.left = slideSize * index + 'px';
};
slides.forEach(setSlidePosition);

function moveToSlide (track, currentSlide, targetSlide){
    track.style.transform = 'translateX(-' + targetSlide.style.left + ')';
    currentSlide.classList.remove('current-slide');
    targetSlide.classList.add('current-slide');
};

Here is the codepen: https://codepen.io/beseu/pen/RwxebYy

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The first one is the only one that is scrolling as that is the one returned from document.querySelector('.carousel_track');. querySelector will only return the first match (null if no match is found). See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector for further reference.

You could tweak things a bit by using querySelectorAll (https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) to get all matching elements. With the HTML provided in the CodePen, you could query for all carousels with .carousel, and set each one up using most of your existing JS. Here's an example - https://codepen.io/brianmarco/pen/WNdaNov .

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda