Jump to content

01Moonlight

Members
  • Posts

    5
  • Joined

  • Last visited

Posts posted by 01Moonlight

  1. Hi - I'm using the W3 Accordion code with the flowing JS.

    <script type="text/javascript">
    var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
      acc.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";
        }
      });
    }
    </script>

     

    However, I would like to only have one tab open at a time. I found a script similar to what I'm looking for at:

    https://stackoverflow.com/questions/45214002/w3-accordion-auto-close-sections-and-open-close-all

    var acc = document.getElementsByClassName("accordion");
    var i;
    
    for (i = 0; i < acc.length; i++) {
      acc[i].onclick = function() {
    
    	if( !this.classList.contains('active') ){
        	closeAll();
        }
    	
      this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight){
          panel.style.maxHeight = null;
        } else {
          panel.style.maxHeight = panel.scrollHeight + "px";
        } 
      }
    }
    
    function openAll(){
        for (i = 0; i < acc.length; i++) {
        	acc[i].classList.add("active");
            acc[i].nextElementSibling.style.maxHeight = acc[i].nextElementSibling.scrollHeight + "px";
        }
    }
    
    function closeAll(){
    	 for (i = 0; i < acc.length; i++) {
        	acc[i].classList.remove("active");
            acc[i].nextElementSibling.style.maxHeight = null;
        }
    }
    
    document.getElementById( 'openAll' ).addEventListener( 'click', openAll);
    document.getElementById( 'closeAll' ).addEventListener( 'click', closeAll);

    However, when I replace the code or put any other JS in, the panels no longer open. I don't know anything about JS so I don't know what's wrong.

    Thanks.

     

×
×
  • Create New...