So as I've slowly been learning JS I've been going through my site to improve any previous code.
One thing I've been doing lately is replacing for loops with forEach and so far all good apart from one which I can't figure out. It's for an accordion which closes one as another opens, but also scrolls the current one into view (it's for a mobile footer menu).
The top first for loop I can solve no problem, but it's the second one in that I'm struggling with and not even sure if it even can be done with forEach:
var acc = document.getElementsByClassName('footer-accordion');
var i;
for (i = 0; i < acc.length; i++) { // I can replace this one with forEach no problem
acc[i].addEventListener('click', function() {
this.classList.toggle('active');
var panel = this.nextElementSibling;
if (panel.style.display === 'block') {
panel.style.display = 'none';
} else {
panel.style.display = 'block';
for (let j = 0; j < acc.length; j++) { // This is the one I am struggling on!!
if (this.classList != acc[j].classList) {
acc[j].classList.remove('active');
acc[j].nextElementSibling.style.display = 'none';
panel.scrollIntoView({
block: 'end',
behavior: 'smooth'
});
}
}
}
});
}
Is something like this not working for you? can you share your html to help with testing?
acc.forEach((current)=>{
if (this.classList != current.classList) {
current.classList.remove('active');
current.nextElementSibling.style.display = 'none';
panel.scrollIntoView({
block: 'end',
behavior: 'smooth'
});
}
})