schweigenderFlugel / portfolio

Link to my portfolio website
https://facu-castro.netlify.app/
0 stars 0 forks source link

Carousel touch #8

Closed schweigenderFlugel closed 1 month ago

schweigenderFlugel commented 1 month ago

One problem that I found is when you're trying to move the carousel of tags using a touch screen. Use the following block of code as a reference:

---
// Carousel.astro
const images = [
  'https://via.placeholder.com/300x200?text=Image+1',
  'https://via.placeholder.com/300x200?text=Image+2',
  'https://via.placeholder.com/300x200?text=Image+3',
];
---

<div class="relative overflow-hidden w-full h-64">
  <div id="carousel" class="flex transition-transform duration-300">
    {images.map((src, index) => (
      <img src={src} alt={`Slide ${index + 1}`} class="w-full h-full object-cover" />
    ))}
  </div>
</div>

<script>
  let startX;
  let currentTranslate = 0;
  let prevTranslate = 0;
  let animationID;
  const carousel = document.getElementById('carousel');

  function touchStart(event) {
    startX = event.touches[0].clientX;
    animationID = requestAnimationFrame(animation);
    carousel.addEventListener('touchmove', touchMove);
    carousel.addEventListener('touchend', touchEnd);
  }

  function touchMove(event) {
    const currentX = event.touches[0].clientX;
    currentTranslate = prevTranslate + currentX - startX;
  }

  function touchEnd() {
    prevTranslate = currentTranslate;
    cancelAnimationFrame(animationID);
    carousel.removeEventListener('touchmove', touchMove);
    carousel.removeEventListener('touchend', touchEnd);
  }

  function animation() {
    carousel.style.transform = `translateX(${currentTranslate}px)`;
    requestAnimationFrame(animation);
  }

  carousel.addEventListener('touchstart', touchStart);
</script>

<style>
  /* Opcional: Estilo personalizado si es necesario */
</style>
schweigenderFlugel commented 1 month ago

This code was included on the code with some modifications.