Search code examples
javascripthtmltoggledisplayhidden

i want a function that toggles between displaying hidden divs in javascript


<div class="toggle-container">
    <div class="1">1</div>
    <div class="1">2</div>
    <div class="1">3</div>
    <div class="1">4</div>
    <div class="1">5</div>
<div>
  <button class="switch">1</button>
  <button class="switch">2</button>
  <button class="switch">3</button>
  <button class="switch">4</button>
  <button class="switch">5</button>
</div>

Please I need to be able to display one div at a time when I click on its corressponding button


Solution

  • If you are trying to control the style with javascript then you can use this slightly modified code:

    <div class="toggle-container">
        <div class="display" id="1">1</div>
        <div class="display" id="2">2</div>
        <div class="display" id="3">3</div>
        <div class="display" id="4">4</div>
        <div class="display" id="5">5</div>
    </div>
    <button class="switch">1</button>
    <button class="switch">2</button>
    <button class="switch">3</button>
    <button class="switch">4</button>
    <button class="switch">5</button>
    <script>
        const checklist = ["1","2","3","4","5"];
        function hideAll(){
            for (var item of checklist){
                document.getElementById(item).style.display = "none";
            }
        }
        function show(id){
            hideAll();
            document.getElementById(id).style.display = "initial";
        }
        const divs = document.querySelectorAll('.switch');
        for (var i=0; i<divs.length; i++){
            let id = checklist[i];
            divs[i].addEventListener('click', function(){show(id)});
        }
    </script>