Toggle Hide Show Multiple sections

Ok, my brains are not firing on all cylinders today. If I even have the brief right, I am sure the solution could be done in a slicker manner.

I’ve used datasets to aid in targeting the right section. data-lastShown, will store the data-section for the last clicked button.

html

<section id="Ayat-1">Ayat 1</section>
<section id="Ayat-2">Ayat 2</section>
<section id="Ayat-3">Ayat 3</section>
<section id="Ayat-4">Ayat 4</section>

<div class='buttons' data-lastShown=''>
  <button data-section='Ayat-1'>Hide Other than Ayat-1</button>
  <button data-section='Ayat-2'>Hide Other than Ayat-2</button>
  <button data-section='Ayat-3'>Hide Other than Ayat-3</button>
  <button data-section='Ayat-4'>Hide Other than Ayat-4</button>
</div>

javascript

function resetSections (sections) {
    sections.forEach((section) => section.classList.remove('hideWithOpacity'))
}

function hideOthers({target}) {
    const showOnly = target.dataset.section
    const parentDataset = target.parentElement.dataset
    const allSections = document.querySelectorAll('section')

    // if a different button is clicked to last time then reset all first
    if (parentDataset.lastShown !== showOnly) resetSections(allSections)

    allSections.forEach((section) => {
        if (section.id !== showOnly) section.classList.toggle('hideWithOpacity')
    })
  
    // store last button clicked in data-lastShown
    parentDataset.lastShown = showOnly
}

const buttons = document.querySelectorAll('.buttons button')
buttons.forEach((button) => button.addEventListener('click', hideOthers))

Note you can swap ‘hideWithOpacity’ to just ‘hide’. Just trying things out.

codepen same as above

1 Like