How to find index of previous active class

I am trying to make a slider. Most of it is working till here, but I am not getting further as I want to find the index of the item which I removed the class as last from.(before the click)

So when I click on a dot, the clicked dot must be enabled and get the active class and the class on the previous active dot needs to be removed.

navDots.addEventListener('click', e => {
         
         // make only dot's clickable
         const targetDot = e.target.closest('.dots');

        // disable NavDots for clicks
        if(!targetDot)return;
            
        //Find the index of the clicked btn
        const dotIndex = Array.from(targetDot.parentNode.children).indexOf(targetDot);
        console.log(dotIndex);

        // Add the active class tot the dot     
        navDots.children[dotIndex].classList.add('active');
       
        //HOW TO REMOVE PREVIOUS DOT ACTIVE style?
            
            //show image with dotIndex
            showImages(dotIndex);
});

Thank you for helping,

r,y.

1 answer

  • answered 2022-05-06 01:31 vanowm

    The most efficient way is to store active element in a variable:

    let activeElement = null;
    navDots.addEventListener('click', e => {
    
        // make only dot's clickable
        const targetDot = e.target.closest('.dots');
    
        // disable NavDots for clicks
        if(!targetDot)return;
    
        //Find the index of the clicked btn
        const dotIndex = Array.from(targetDot.parentNode.children).indexOf(targetDot);
        console.log(dotIndex);
    
        // remove previous active class
        activeElement && activeElement.classList.remove("active");
    
        // save new active element
        activeElement = navDots.children[dotIndex];
        // Add the active class tot the dot     
        activeElement.classList.add('active');
    
        //HOW TO REMOVE PREVIOUS DOT ACTIVE style?
    
        //show image with dotIndex
        showImages(dotIndex);
    });
    
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum