Carrossel de imagens com bug

HTML

CSS

JavaScript

11/05/2023

Buenas!

Criei (adaptando um código que achei na net) um carrossel de imagens, porem quando clica na seta para mudar a imagem na primeira vez que a pagina carregou, a imagem se move em pedaços, se atualizar e clicar para mudar, a imagem muda inteira...

Desconfio que o problema esteja ao pegar o tamanho da tela com
clientWidth
que pelo que vi no console, vem com um valor no primeiro load, e ao atualizar fica com outro... Mas ainda não saquei como resolver...

Se alguém tiver uma sugestão fico grato

window.addEventListener(''DOMContentLoaded'', function () {

    //Script que injeta as imagens na pagina.

    const imgList = [ 
        "https://files.tecnoblog.net/wp-content/uploads/2021/07/7-jogos-de-Star-Wars-para-baixar-no-PC-e-consoles-tommy-van-kessel-unsplash.jpg",
        "https://disneyplusbrasil.com.br/wp-content/uploads/2022/02/Rey-Skywalker.jpg",
        "https://vejasp.abril.com.br/wp-content/uploads/2021/07/mandalorian.jpg?quality=70&strip=info&w=1280&h=720&crop=1",
        "https://upload.wikimedia.org/wikipedia/pt/0/0e/Star_Wars_The_Last_Jedi.png",
        "https://sm.ign.com/ign_br/news/s/star-wars-/star-wars-celebration-2023-everything-announced-at-lucasfilm_y99h.jpg",
        "https://img.freepik.com/fotos-premium/cachorro-golden-retriever-fazendo-truque-de-patinha-no-cinza_143092-1673.jpg?w=900",
        "https://img.freepik.com/fotos-gratis/colagem-de-animal-de-estimacao-bonito-isolada_23-2150007407.jpg?w=826&t=st=1683309195~exp=1683309795~hmac=c46ffb18700a3927a6110ddecbe67287699829c6b49b928550e2aee4f1240ffd",
        "https://img.freepik.com/fotos-gratis/isolado-feliz-sorridente-cao-fundo-branco-retrato-4_1562-693.jpg?w=900&t=st=1683309164~exp=1683309764~hmac=dc461720d01367824920d65a1b8923c6ab1de7ca76c303e8426020d52f0415f7",
        "https://img.freepik.com/fotos-gratis/cao-pug-isolado-em-um-fundo-branco_2829-11416.jpg?w=826&t=st=1683309193~exp=1683309793~hmac=43c07318d4231e94a0ce33a4c4d82759232ba0157331c0a7a36756d046b0dd16"
    ];
    
    var carousel = document.querySelector(".carousel");
    
    for (var i = 0; i < imgList.length; i++) {
        const img = document.createElement("img");
        img.src = imgList[i];
        img.alt = "Imagem " + (i+1);
        carousel.appendChild(img);
    }



// Script com o arrastar do mouse e as funções das setas laterais

const firstImg = document.querySelectorAll("img")[0],
arrowIcons = document.querySelectorAll(".wrapper i");

let isDragStart = false, isDragging = false, prevPageX, prevScrollLeft, positionDiff;

const showHideIcons = () => {
    let scrollWidth = carousel.scrollWidth - carousel.clientWidth;
    arrowIcons[0].style.display = carousel.scrollLeft === 0 ? "none" : "block";
    arrowIcons[1].style.display = carousel.scrollLeft - scrollWidth > -1 ? "none" : "block";
}

arrowIcons.forEach(icon => {
    let firstImgWidth = firstImg.clientWidth + 14;
    icon.addEventListener("click", () => {
        carousel.scrollLeft += icon.id === "left" ? -firstImgWidth : firstImgWidth;
        setTimeout(() => showHideIcons(), 60);
    });
});

const autoSlide = () => {
    if(carousel.scrollLeft - (carousel.scrollWidth - carousel.clientWidth) > -1 || carousel.scrollLeft <= 0) return;
    
    positionDiff = Math.abs(positionDiff);
    let firstImgWidth = firstImg.clientWidth + 14;
    let valDifference = firstImgWidth - positionDiff;

    if(carousel.scrollLeft > prevScrollLeft) {
        return carousel.scrollLeft += positionDiff > firstImgWidth / 4 ? valDifference : -positionDiff;
    }
    carousel.scrollLeft -= positionDiff > firstImgWidth / 4 ? valDifference : -positionDiff;
}

const dragStart = (e) => {
    isDragStart = true;
    prevPageX = e.pageX || e.touches[0].pageX;
    prevScrollLeft = carousel.scrollLeft;
}

const dragging = (e) => {
    if(!isDragStart) return;
    isDragging = true;
    carousel.classList.add("dragging");
    positionDiff = (e.pageX || e.touches[0].pageX) - prevPageX;
    carousel.scrollLeft = prevScrollLeft - positionDiff;
    showHideIcons();
}

const dragStop = () => {
    isDragStart = false;
    carousel.classList.remove("dragging");

    if(!isDragging) return;
    isDragging = false;
    autoSlide();
}

carousel.addEventListener("mousedown", dragStart);
carousel.addEventListener("touchstart", dragStart);

document.addEventListener("mousemove", dragging);
carousel.addEventListener("touchmove", dragging);

document.addEventListener("mouseup", dragStop);
document.addEventListener("mouseleave", dragStop);
carousel.addEventListener("touchend", dragStop);

});


<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Carrocel responsivo arrasta com mouse</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
    <script src="script.js" ></script>
    
  </head>
  <body>
    <div class="wrapper">
      <i id="left" class="fa-solid fa-angle-left"></i>
      <div class="carousel">

      </div><!--carousel-->
      <i id="right" class="fa-solid fa-angle-right"></i>
    </div><!--wrapper-->
    
  </body>
</html>



*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;

}
body{
  display: flex;
  padding: 0 35px;
  min-height: 100vh;
  align-items: center;
  justify-content: center;
  background: #343F4F;
}
.wrapper{
  display: flex;
  max-width: 1200px;
  position: relative;
}
.wrapper i{
  top: 50%;
  height: 44px;
  width: 44px;
  color: #343F4F;
  cursor: pointer;
  font-size: 1.15rem;
  position: absolute;
  text-align: center;
  line-height: 44px;
  background: #fff;
  border-radius: 50%;
  transform: translateY(-50%);
  transition: transform 0.1s linear;
}
.wrapper i:active{
  transform: translateY(-50%) scale(0.9);
}
.wrapper i:hover{
  background: #f2f2f2;
}
.wrapper i:first-child{
  left: -22px;
  display: none;
}
.wrapper i:last-child{
  right: -22px;
}
.wrapper .carousel{
  font-size: 0px;
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  scroll-behavior: smooth;
}
.carousel.dragging{
  cursor: grab;
  scroll-behavior: auto;
}
.carousel.dragging img{
  pointer-events: none;
}
.carousel img{
  height: 340px;
  object-fit: cover;
  user-select: none;
  margin-left: 14px;
  width: calc(100% / 3);
}
.carousel img:first-child{
  margin-left: 0px;
}

@media screen and (max-width: 900px) {
  .carousel img{
    width: calc(100% / 2);
  }
}

@media screen and (max-width: 550px) {
  .carousel img{
    width: 100%;
  }
}
Eduardo

Eduardo

Curtidas 0

Respostas

Frank Hosaka

Frank Hosaka

11/05/2023

Eu mudei as aspas duplas para simples:

window.addEventListener(''DOMContentLoaded'', function () 
 





GOSTEI 0
Frank Hosaka

Frank Hosaka

11/05/2023

Eu mudei as aspas duplas para simples:

window.addEventListener('DOMContentLoaded', function () 
 





GOSTEI 0
Eduardo

Eduardo

11/05/2023

Eu mudei as aspas duplas para simples:

window.addEventListener('DOMContentLoaded', function () 
 







Obrigado pela resposta, mas no meu código já esta com aspa simples, o quote do forum que mudou para dupla...
GOSTEI 0
POSTAR