Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Block a JavaScript function in a page

I have a javascript function for a slider in the JS file of my site. When we are in a page where the slider is not called or there is no trigger element, it displays an error in the console "Uncaught TypeError: Cannot read properties of null (reading ‘querySelector’) ", This error is not displayed when the slider is in the page.

I would like to know how to avoid this error, and how to prevent this function from loading in pages where this slider is not present?

function slider(set) {
    const sliderContainer = document.querySelector(set.name),
        slider = sliderContainer.querySelector('.slider'),
        sliderItem = slider.querySelectorAll('.slider__item'),
    sliderArrows = sliderContainer.querySelectorAll('.arrows__item');
    
    let dotsCreate,
        dotsClass,
        dotsFunk,
        numberSlider,
        numberSliderWork,
        sliderExecutionLine,
    sliderExecutionLineWork;
    
    // calculate the maximum width of all slides
    function forSliderItem(t) {
        t = 0;
        for(let i = 0; i < sliderItem.length - 1; i++) {
            t += sliderItem[i].clientWidth;
        }
        return t;
  }
  
    let maxWidth = forSliderItem(sliderItem), // maximum width of all slides
        slidWidth = 0, // main variable for calculating the movement of the slider
    count = 0; // counter
    //===== flip left
    sliderArrows[0].addEventListener('click', function() {
        if(count !== 0) {
            count--;
            slidWidth -= sliderItem[count].clientWidth;
            slider.style.transform = `translateX(-${slidWidth}px)`;
        } else {
            count = sliderItem.length - 1;
            slidWidth = maxWidth;
            slider.style.transform = `translateX(-${slidWidth}px)`;
    }
        if(set.dots) {
            dotsFunk();
        }
        if(set.numberSlid) {
            numberSliderWork(count);
        }
        if(set.line) {
            sliderExecutionLineWork(count);
        }
  });
  
    //===== flip right  
    sliderArrows[1].addEventListener('click', function() {
        if(count < sliderItem.length - 1) {
            count++;
            slidWidth += sliderItem[count].clientWidth;
            slider.style.transform = `translateX(-${slidWidth}px)`;
        } else {
            count = 0;
            slidWidth = 0;
            slider.style.transform = `translateX(-${slidWidth}px)`;
    }
        if(set.dots) {
            dotsFunk();
        }
        if(set.numberSlid) {
            numberSliderWork(count);
        }
        if(set.line) {
            sliderExecutionLineWork(count);
        }
  });
  
    //===== dots
    if(set.dots) {
        dotsCreate = function() {
            const dotContainer = document.createElement('div'); // create dots container
            dotContainer.classList.add('dots');
            // create the required number of dots and insert a container into the dots
            sliderItem.forEach(() => {
                let dotsItem = document.createElement('span');
                dotContainer.append(dotsItem);
            });
            sliderContainer.append(dotContainer);
        };
    dotsCreate();
    
        // add the class to the desired dots, and remove from the rest
        dotsClass = function(remove, add) {
            remove.classList.remove('dots_active');
            add.classList.add('dots_active');
    };
    
        // move slides by clicking on the dot
        dotsFunk = function() {
            const dotsWork = sliderContainer.querySelectorAll('.dots span'); // we get dots
            dotsWork.forEach((item, i) => {
                dotsClass(dotsWork[i], dotsWork[count]);
                item.addEventListener('click', function() {
                    count = i;
                    // multiply the slide size by the number of the dots, and get the number by which you need to move the slider
                    slidWidth = sliderItem[0].clientWidth * i;
                    slider.style.transform = `translateX(-${slidWidth}px)`;
                    for(let j = 0; j < dotsWork.length; j++) {
                        dotsClass(dotsWork[j], dotsWork[count]);
                    }
                    if(set.dots && set.numberSlid) {
                        numberSliderWork(count);
                    }
                    if(set.line) {
                        sliderExecutionLineWork(count);
                    }
                }); 
            });
        };
        dotsFunk();
  }
  
    //=====  count slider
    if(set.numberSlid) {
        numberSlider = function(item) {
            const countContainer = document.createElement('div'),
                sliderNumber = document.createElement('span'),
                slash = document.createElement('span'),
                allSliderNumber = document.createElement('span');
        casClient = document.createElement('p');
            sliderNumber.innerHTML = item + 1;
      casClient.innerHTML = 'Cas client N°';
            slash.innerHTML = '/';
            allSliderNumber.innerHTML = sliderItem.length;
            countContainer.classList.add('count-slides');
            countContainer.append(casClient, sliderNumber, slash, allSliderNumber);
            sliderContainer.append(countContainer);
        };
    numberSlider(0);
    
        numberSliderWork = function(item) {
            const sliderNumberNow = sliderContainer.querySelector('.count-slides span');
            sliderNumberNow.innerHTML =  item + 1;
            if(set.line) {
                sliderExecutionLineWork(item);
            }
        };
  }
}
slider({
    name: ".video_users",
    numberSlid: true
});
<!DOCTYPE html>
<html lang="fr">

<head>
  <title>Example of a page without the slider</title>
</head>

<body class="error_404">
  <h1>Example of a page without the slider</h1>

  <script src="media/js/faveod.js" async></script>
</body>

</html>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just return if the element isn’t present if you don’t want it to show an error.

const sliderContainer = document.querySelector(set.name);
if (!sliderContainer) return;
const slider = sliderContainer.querySelector('.slider'),
      sliderItem = slider.querySelectorAll('.slider__item'),
      sliderArrows = sliderContainer.querySelectorAll('.arrows__item');

If you want it to only execute on certain pages, then just add:

if (location.pathname !== '/the/page/with/slider') return;

to the beginning of the function

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading