Add conditions to the general slider js

Viewed 146

I have the same slider on my site on two pages, for which one common js file is used

 // Slider
 const slider = document.getElementById('generalSlider');
 const sliderRow = document.getElementById('generalSliderRow');
 const slides = document.querySelectorAll('.general');
 const INTERVAL = 6000;
 let timer = null;
 
 initSlider(slider, sliderRow, slides);
 
 function initSlider(slider, sliderRow, slides) {
     const slidesLength = slides.length;
 
     let allowShift = true;
     const CLONES_COUNT = 1;
     let slideWidth = slider.offsetWidth;
     const firstSlide = slides[0];
 
     let currentOffset = -slideWidth * CLONES_COUNT;
     let currentIndex = 1;
 
     slides.forEach(slide => {
         slide.style.width = slideWidth + 'px';
     });
 
     const appendSlides = [];
     const prependSlides = [];
 
     for (let i = 1; i <= CLONES_COUNT; i++) {
         prependSlides.push(slides[slidesLength - i].cloneNode(true));
         appendSlides.push(slides[i - 1].cloneNode(true));
     }
 
     prependSlides.reverse().forEach(slide => {
         sliderRow.insertBefore(slide, firstSlide);
     });
 
     appendSlides.forEach(slide => {
         sliderRow.appendChild(slide);
     });
 
     sliderRow.style.width = (slideWidth * (slidesLength + CLONES_COUNT * 2)) + 'px';
     sliderRow.style.transform = `translateX(${currentOffset}px)`;
 
     document.querySelector(`.general:nth-child(${currentIndex + CLONES_COUNT})`).classList.add('active');
     document.getElementById('navText').innerHTML = `${currentIndex} of ${slidesLength}`;
 
     const prevArrow = document.getElementById('prevArrow');
     const nextArrow = document.getElementById('nextArrow');
 
     prevArrow.addEventListener('click', () => {
         shiftSlide(-1);
         stopAutoplay();
     });
 
     nextArrow.addEventListener('click', () => {
         shiftSlide(1);
         stopAutoplay();
     });
 
     sliderRow.addEventListener('transitionend', checkIndex);
     sliderRow.addEventListener('click', stopAutoplay);
 
     function shiftSlide(dir, action = null) {
         sliderRow.classList.add('shifting');
 
         if (action) {
             currentOffset = posInitial;
         }
 
         if (allowShift) {
             if (dir === 1) {
                 currentOffset -= slideWidth;
                 sliderRow.style.transform = `translateX(${currentOffset}px)`;
                 currentIndex++;
             } else if (dir === -1) {
                 currentOffset += slideWidth;
                 sliderRow.style.transform = `translateX(${currentOffset}px)`;
                 currentIndex--;
             }
 
             document.querySelector('.general.active').classList.remove('active');
             document.querySelector(`.general:nth-child(${currentIndex + CLONES_COUNT})`).classList.add('active');
         }
 
         allowShift = false;
     }
 
     function checkIndex (){
         sliderRow.classList.remove('shifting');
 
         if (currentIndex === 0) {
             currentOffset = (-slideWidth * CLONES_COUNT) + (-slideWidth * (slidesLength - 1));
             sliderRow.style.transform = `translateX(${currentOffset}px)`;
             currentIndex = slidesLength;
         }
 
         if (currentIndex > slidesLength) {
             currentOffset = -slideWidth * CLONES_COUNT;
             sliderRow.style.transform = `translateX(${currentOffset}px)`;
             currentIndex = 1;
         }
 
         document.getElementById('navText').innerHTML = `${currentIndex} of ${slidesLength}`;
         document.querySelector('.general.active').classList.remove('active');
         document.querySelector(`.general:nth-child(${currentIndex + CLONES_COUNT})`).classList.add('active');
 
         allowShift = true;
     }
 
     let posX1 = 0;
     let posX2 = 0;
     let posInitial;
     let posFinal;
     const threshold = 100;
 
     // sliderRow.onmousedown = dragStart;
     // sliderRow.addEventListener('touchstart', dragStart);
     // sliderRow.addEventListener('touchend', dragEnd);
     // sliderRow.addEventListener('touchmove', dragAction);
 
     function dragStart (e) {
         e = e || window.event;
         e.preventDefault();
         if (!allowShift) {
             return;
         }
         posInitial = currentOffset;
 
         if (e.type == 'touchstart') {
             posX1 = e.touches[0].clientX;
         } else {
             posX1 = e.clientX;
             document.onmouseup = dragEnd;
             document.onmousemove = dragAction;
         }
     }
 
     function dragAction (e) {
         e = e || window.event;
 
         if (e.type == 'touchmove') {
             posX2 = posX1 - e.touches[0].clientX;
             posX1 = e.touches[0].clientX;
         } else {
             posX2 = posX1 - e.clientX;
             posX1 = e.clientX;
         }
         currentOffset = currentOffset - posX2;
         sliderRow.style.transform = `translateX(${currentOffset}px)`;
     }
 
     function dragEnd (e) {
         posFinal = currentOffset;
         if (posFinal - posInitial < -threshold) {
             shiftSlide(1, 'drag');
         } else if (posFinal - posInitial > threshold) {
             shiftSlide(-1, 'drag');
         } else {
             currentOffset = posInitial;
             sliderRow.style.transform = `translateX(${currentOffset}px)`;
         }
 
         document.onmouseup = null;
         document.onmousemove = null;
     }
 
     window.addEventListener('resize', () => {
         resizeSlider();
     })
 
     function resizeSlider() {
         const newSlideWidth = slider.offsetWidth;
 
         if (newSlideWidth === slideWidth) return;
 
         slideWidth = newSlideWidth;
 
         document.querySelectorAll('.general').forEach(slide => {
             slide.style.width = slideWidth + 'px';
         });
 
         currentOffset = (-slideWidth * CLONES_COUNT) + (-slideWidth * (currentIndex - 1));
 
         sliderRow.style.width = (slideWidth * (slidesLength + CLONES_COUNT * 2)) + 'px';
         sliderRow.style.transform = `translateX(${currentOffset}px)`;
     }
 
     function startAutoplay() {
         timer = setInterval(() => {
             shiftSlide(1);
         }, INTERVAL)
     }
 
     function stopAutoplay() {
         clearInterval(timer);
         timer = null;
     }
 
     startAutoplay();
 }

But now on one of the pages I need to slightly change the js file, but literally a couple of lines of code

I need to add this

let CLONES_COUNT;

if (slidesLength < 2) {
    CLONES_COUNT = 0;
} else {
    CLONES_COUNT = 1;
}

and

if (slidesLength > 1) {
    startAutoplay();
}

Is it possible to make some condition to use a specific piece of code in a js file for a specific page? so as not to make exactly the same file where there will be minimal changes

Something like

if (RouteName() === 'home') {
const CLONES_COUNT = 1;
}

if (RouteName() === 'blog'){
let CLONES_COUNT;

if (slidesLength < 2) {
    CLONES_COUNT = 0;
} else {
    CLONES_COUNT = 1;
}
}

js

function initSlider(slider, sliderRow, slides, CLONES_COUNT, doAutoPlay) {
. . .
}

blade.php

@section('scripts')
<script src="/js/slider.js"></script>
<script defer>$( document ).ready(function() {initSlider(slider, sliderRow, slides, (slides.length < 2) ? 0 : 1, slides.length > 1)})</script>
@endsection
2 Answers

You could add a parameter to your initSlider function, and remove the calling of it from your common.js

function initSlider(slider, sliderRow, slides, CLONES_COUNT) {
  // ...
}

And then call it on home with initSlider(slider, sliderRow, slides, 1) or on blog with:

const CLONES_COUNT = (slidesLength < 2) ? 0 : 1;
initSlider(slider, sliderRow, slides, CLONES_COUNT);

This gives the option to configure it differently on different pages in the future as well.

Using pathname property of the Location interface, you can try this :

if (window.location.pathname.startWith('/home')) {
  const CLONES_COUNT = 1;
}

if (window.location.pathname.startWith('/blog')){
  let CLONES_COUNT;

  if (slidesLength < 2) {
    CLONES_COUNT = 0;
  } else {
    CLONES_COUNT = 1;
  }
}
Related