1

Tengo el siguiente código.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">

        .sliderModalImage {
            height: 100vh;
            display: inline-flex;
            overflow: hidden;
            transform: translateX(0);
            transition: transform 0.3s ease-out;
            cursor: grab;
        }

        .slide {
            max-height: 100vh;
            width: 100vw;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 1rem;
            user-select: none;
        }

        .slide img {
            max-width: 100%;
            max-height: 60%;
            transition: transform 0.3s ease-in-out;
        }

        .btn {
            background-color: #444;
            color: #fff;
            text-decoration: none;
            padding: 1rem 1.5rem;
        }

        .grabbing {
            cursor: grabbing;
        }

        .grabbing .slide img {
            transform: scale(0.9);
        }
        .contenedor {
            align-content: center;
            align-items: center;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1 class="contenedor" id="contenedor1">slide 1</h1>
    <h1 class="contenedor" id="contenedor2">slide 2</h1>
    <h1 class="contenedor" id="contenedor3">slide 3</h1>
    <div class="sliderModalImage" >
        <div class="slide" id="0">
            <img src="https://images.unsplash.com/photo-1584438784894-089d6a62b8fa?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8cGhvbmV8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" alt="" />
      </div>
      <div class="slide" id="1">
            <img src="https://images.unsplash.com/photo-1525598912003-663126343e1f?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NHx8cGhvbmV8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" alt="" />
      </div>
      <div class="slide" id="2">
            <img src="https://images.unsplash.com/photo-1534536281715-e28d76689b4d?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTJ8fHBob25lfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" alt="" />
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('.contenedor').on('click', function() {
                console.log($(this).attr('id'));
                var id = $(this).attr('id');
                $('.contenedor').css('display', 'none');
                $('.contenedor').css('display', 'block');
            });
        });
        const slider = document.querySelector('.sliderModalImage'),
          slides = Array.from(document.querySelectorAll('.slide'))

        let isDragging = false,
          startPos = 0,
          currentTranslate = 0,
          prevTranslate = 0,
          animationID = 0,
          currentIndex = 0

        slides.forEach((slide, index) => {
          const slideImage = slide.querySelector('img');
          console.log(slideImage);
          slideImage.addEventListener('dragstart', (e) => e.preventDefault());

          // Touch events
          slide.addEventListener('touchstart', touchStart(index));
          slide.addEventListener('touchend', touchEnd);
          slide.addEventListener('touchmove', touchMove);

          // Mouse events
          slide.addEventListener('mousedown', touchStart(index));
          slide.addEventListener('mouseup', touchEnd);
          slide.addEventListener('mouseleave', touchEnd);
          slide.addEventListener('mousemove', touchMove);
        });

        window.oncontextmenu = function (event) {
          event.preventDefault();
          event.stopPropagation();
          return false;
        }

        function touchStart(index) {
          return function (event) {
            currentIndex = index
            startPos = getPositionX(event);
            console.log(startPos);
            isDragging = true;
            animationID = requestAnimationFrame(animation);
            slider.classList.add('grabbing');
          }
        }

        function touchEnd() {
            isDragging = false
            cancelAnimationFrame(animationID);

            const movedBy = currentTranslate - prevTranslate;

            if (movedBy < -100 && currentIndex < slides.length - 1) currentIndex += 1

            if (movedBy > 100 && currentIndex > 0) currentIndex -= 1

            setPositionByIndex();

            slider.classList.remove('grabbing');
        }

        function touchMove(event) {
            if (isDragging) {
                const currentPosition = getPositionX(event);
                currentTranslate = prevTranslate + currentPosition - startPos;
            }
        }

        function getPositionX(event) {
            return event.type.includes('mouse') ? event.pageX : event.touches[0].clientX;
        }

        function animation() {
            setSliderPosition();
            if (isDragging) requestAnimationFrame(animation);
        }

        function setSliderPosition() {
            slider.style.transform = `translateX(${currentTranslate}px)`;
        }

        function setPositionByIndex() {
            currentTranslate = currentIndex * -window.innerWidth;
            prevTranslate = currentTranslate;
            setSliderPosition();
        }

    </script>
</body>
</html>

No encuentro la manera de hacer que si yo hago click en el slider 2 se me despliegue el slider mostrando la imagen con id 2.

Ojalá alguien pueda ayudarme.

1
  • Lo siento no entiendi tu pregunta, quieres mostrar el slider dependiendo de que?
    – Christian
    Commented el 17 mar. 2021 a las 18:53

1 respuesta 1

2

No necesitas usar IDs, porque no coinciden los de contenedor con las imágenes. Es suficiente con usar el índice, porque es la misma cantidad de contenedores e imágenes.

En tu código, estabas usando jQuery solo para la función que se ejecuta al cargar la página, pero no es necesario, se puede lograr que el slider funcione con Javascript puro, solo necesitas recorrer los contenedores y asignar evento usando el índice para mostrar la imagen correspondiente.

// Ejecutar cuando se haya cargado el DOM
document.addEventListener('DOMContentLoaded', () => {
    // Obtener contenedores y recorrer con su respectivo índice
    document.querySelectorAll('.contenedor').forEach((item, index) => {
        // Asignar evento para escuchar clics
        item.addEventListener('click', () => {
            // Usar índice del contenedor para actualizar el elemento a mostrar
            currentIndex = index;
            // Mostrar slider
            setPositionByIndex();
        });
    });
});

const slider = document.querySelector('.sliderModalImage'),
          slides = Array.from(document.querySelectorAll('.slide'))

        let isDragging = false,
          startPos = 0,
          currentTranslate = 0,
          prevTranslate = 0,
          animationID = 0,
          currentIndex = 0

        slides.forEach((slide, index) => {
          const slideImage = slide.querySelector('img');
          // console.log(slideImage);
          slideImage.addEventListener('dragstart', (e) => e.preventDefault());

          // Touch events
          slide.addEventListener('touchstart', touchStart(index));
          slide.addEventListener('touchend', touchEnd);
          slide.addEventListener('touchmove', touchMove);

          // Mouse events
          slide.addEventListener('mousedown', touchStart(index));
          slide.addEventListener('mouseup', touchEnd);
          slide.addEventListener('mouseleave', touchEnd);
          slide.addEventListener('mousemove', touchMove);
        });

        window.oncontextmenu = function (event) {
          event.preventDefault();
          event.stopPropagation();
          return false;
        }

        function touchStart(index) {
          return function (event) {
            currentIndex = index
            startPos = getPositionX(event);
            console.log(startPos);
            isDragging = true;
            animationID = requestAnimationFrame(animation);
            slider.classList.add('grabbing');
          }
        }

        function touchEnd() {
            isDragging = false
            cancelAnimationFrame(animationID);

            const movedBy = currentTranslate - prevTranslate;

            if (movedBy < -100 && currentIndex < slides.length - 1) currentIndex += 1

            if (movedBy > 100 && currentIndex > 0) currentIndex -= 1

            setPositionByIndex();

            slider.classList.remove('grabbing');
        }

        function touchMove(event) {
            if (isDragging) {
                const currentPosition = getPositionX(event);
                currentTranslate = prevTranslate + currentPosition - startPos;
            }
        }

        function getPositionX(event) {
            return event.type.includes('mouse') ? event.pageX : event.touches[0].clientX;
        }

        function animation() {
            setSliderPosition();
            if (isDragging) requestAnimationFrame(animation);
        }

        function setSliderPosition() {
            slider.style.transform = `translateX(${currentTranslate}px)`;
        }

        function setPositionByIndex() {
            currentTranslate = currentIndex * -window.innerWidth;
            prevTranslate = currentTranslate;
            setSliderPosition();
        }
        .sliderModalImage {
            height: 100vh;
            display: inline-flex;
            overflow: hidden;
            transform: translateX(0);
            transition: transform 0.3s ease-out;
            cursor: grab;
        }

        .slide {
            max-height: 100vh;
            width: 100vw;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 1rem;
            user-select: none;
        }

        .slide img {
            max-width: 100%;
            max-height: 60%;
            transition: transform 0.3s ease-in-out;
        }

        .btn {
            background-color: #444;
            color: #fff;
            text-decoration: none;
            padding: 1rem 1.5rem;
        }

        .grabbing {
            cursor: grabbing;
        }

        .grabbing .slide img {
            transform: scale(0.9);
        }
        .contenedor {
            align-content: center;
            align-items: center;
            text-align: center;
        }
    <h1 class="contenedor" id="contenedor1">slide 1</h1>
    <h1 class="contenedor" id="contenedor2">slide 2</h1>
    <h1 class="contenedor" id="contenedor3">slide 3</h1>
    <div class="sliderModalImage" >
        <div class="slide" id="0">
            <img src="https://images.unsplash.com/photo-1584438784894-089d6a62b8fa?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8cGhvbmV8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" alt="" />
      </div>
      <div class="slide" id="1">
            <img src="https://images.unsplash.com/photo-1525598912003-663126343e1f?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NHx8cGhvbmV8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" alt="" />
      </div>
      <div class="slide" id="2">
            <img src="https://images.unsplash.com/photo-1534536281715-e28d76689b4d?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTJ8fHBob25lfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" alt="" />
      </div>
    </div>

1
  • Era exactamente lo que necesitaba, muchísimas gracias. Commented el 17 mar. 2021 a las 19:11

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.