How to write a function for JS correctly?

  • 0
    Friends help to solve the problem. There is a layout.
    <div class="slider__dots-inner">
            <div class="slider__dots-item"><span class="slider__dots-item--visited">блок 1</span></div>
            <div class="slider__dots-item"><span>блок 2</span></div>
            <div class="slider__dots-item"><span>блок 3</span></div>
            <div class="slider__dots-item"><span>блок 4</span></div>
          </div>

    These are the switches for the slider, the first one always has the slider__dots-item - visited class when loading, it is necessary to remove the active slider__dots-item - visited class when you click on any of the block and add it to a new block. C JS just started to understand from that apparently I'm dull. As I tried to solve.
    let dots = document.querySelectorAll('.slider__dots-item');
        let addThumbnailClickHandler = function (dot) {
            dot.addEventListener('click', function () {
                dot.firstChild.classList.remove('slider__dots-item--visited');
                this.firstChild.classList.add('slider__dots-item--visited');
            });
        };
        for (let i = 0; i < dots.length; i++) {
            addThumbnailClickHandler(dots[i]);
        }

    The problem is that when the page is loaded, the loop is executed immediately; when the page is clicked, the class is added, but not removed from the previous elements. In general, I do not know how to make it so that the loop would be in a function that is triggered when clicking on any of the elements, for one element I know how to do it, but for many I don't catch up. It just turns out a vicious circle, to monitor many blocks you need a cycle, and to call a function for any of the blocks, you need a cycle again.
    JavaScript Aiden Foster, Apr 18, 2020

  • 1 Answers
  • 0
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!