Javascript Gallery: click button doesn't remove hide

Viewed 26

My problem is when I click my buttons they doesn't remove the hide, it just work with the "all", also I tried to change getElementsByClassName() instead of querySelectorAll.

I have no idea what else to do. :(

I cannot show the HTML because it say I have too much code and need to add more details, but I'm pretty sure HTML is correct.

JS

let list = document.getElementsByClassName('list');
let itemBox = document.getElementsByClassName('itemBox');

for (let i = 0; i < list.length; i++) {
    list[i].addEventListener('click', function(){
        for (let j = 0; j < list.length; j++) {
            list[j].classList.remove('active');
        }
        this.classList.add('active');

        let dataFilter = this.getAttribute('data-filter');

        for (let k = 0; k < itemBox.length; k++) {
            itemBox[k].classList.remove('active');
            itemBox[k].classList.add('hide');
            
            if(itemBox[k].getAttribute('data-item') == dataFilter || dataFilter == "all"){
                itemBox[k].classList.remove('hide');
                itemBox[k].classList.add('active');
            }
        }
    });
}

I'm gonna cry, this is my first time here :')

1 Answers

Instead of using 2 class hide and active, how about simplify to using just 1 class active? Then you can use this.classList.toggle('active'), this will add 'active' if there is no active in the classList and remove 'active' if there is active in the classList.

https://www.w3schools.com/howto/howto_js_toggle_class.asp

Related