Accordion Code

Page section: playground

The example page is in the blank section.

So some simple code for making a set of accordion drop downs

<script>
    // Add your JavaScript here...

    document.addEventListener('click', (event) => {
        if ( !event.target.classList.contains('accordion-toggle')) return;
        
        if ( !content) return;
        console.log(content);
        content.classList.toggle('is-open');
        event.preventDefault();
    }, false)
</script>

This works by first adding an event listener to anywhere on the whole document. This is linked to a callback function with the keyword false applied to use capture1. To test this is working an output to console.log was temporarily included.

Next an if statement is used. If the click didn’t emanate from an element containing the class accordion-toggle this was halted with the return keyword.

Next a variable called content was created:

const content = document.querySelector(event.target.hash);

More advanced

document.addEventListener('click', (event) => {
    if ( !event.target.classList.contains('accordion-toggle')) return;
    
    const content = document.querySelector(event.target.hash);
    if ( !content) return;

    // prevent default link behaviour
    event.preventDefault();

    // check if our content area is already is-open

    if ( content.classList.contains('is-open') ) {
        content.classList.remove('is-open');
        return
    }
    
    const accordions = document.querySelectorAll('.accordion');
    
    accordions.forEach((acdn) => {
        acdn.classList.remove('is-open');
    })
    
    content.classList.add('is-open');

    // console.log(content);
}, false)

The CSS

This uses a white to black radial gradient in overlay mode.


  1. He doesn’t explain use capture in the video. ↩︎