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

How can I optimize this code that I wrote to make an accordion?

dear friends, I am just learning javascript and I wrote a code to make an accordion, but I feel that there are much better ways to implement this accordion, I would be grateful if you could guide me with the methods Get to know better.
This is the code I wrote:

const inputs = document.querySelectorAll('input');
const contents = document.querySelectorAll('.content')

let activeTarget;
for (let i = 0; i < contents.length; i++) {
    inputs[i].addEventListener("click",
        (event) => {
            if (contents[i].classList.value === "content open") {
                contents[i].classList.remove('open')
            }
            else if (activeTarget !== undefined) {
                activeTarget.classList.remove('open')
                contents[i].classList.add('open')
                activeTarget = contents[i]
            } else {
                contents[i].classList.add('open')
                activeTarget = contents[i];
            }
        }
        )
}

>Solution :

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

Reduce the else if and else into just one else, then check if activeTarget is undefined in the new else. This reduces duplicated code.

Then let’s change the condition in the if to use contains instead. This will be safer, because you don’t check if the class list is exactly content open. Instead you only test if the element has the open class.

if (contents[i].classList.contains("open")) {
    contents[i].classList.remove('open')
} else {
    if (activeTarget !== undefined)
        activeTarget.classList.remove('open')
    contents[i].classList.add('open')
    activeTarget = contents[i]
}
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