Search code examples
javascriptnavigationdropdown

Javascript onClick() Requiring Multiple Clicks


Good Morning --

I have read through multiple posts with a very similar issue to mine but I still am unable to find a feasible solution. My sideNav is requiring an initial click before it begins working on every click and my dropdown boxes are requiring me double click before anything happens. I have been attempting to fix this for a few days now and was hoping someone here could help.

I have attached my code below. Thanks everyone for taking the time out of your day to help.

https://codepen.io/Bryant_Mitchell/pen/KKPbQLy

    function sideBar() {
      var sideBar = document.getElementById("sideBar"),
      main = document.getElementById("main");
      sideBar.style.width = sideBar.style.width === "250px" ? '0' : '250px';
      main.style.marginLeft = main.style.marginLeft === "250px" ? '0' :  '250px';
    }

function collapseButton() {
  var coll = document.getElementsByClassName("dropdown");
  var i;

      for (i = 0; i < coll.length; i++) {
        coll[i].addEventListener("click", function() {
          this.classList.toggle("active");
          var content = this.nextElementSibling;
          if (content.style.maxHeight){
            content.style.maxHeight = null;
          } else {
            content.style.maxHeight = content.scrollHeight + "px";
          }
        });
      }
  }

P.S. one additional issues I am having but it does not take any priority, when hiding my sideNav it tends to push the content down and is unsightly. I know I can increase the size of the navigation and it will fix this issue but I was wandering if there was any other way to fix it. Again, this isn't really a priority for me but figured I would ask here instead of making another post later.


Solution

  •   function sideBar() {
    
      var sideBar = document.getElementById("sideBar"),
      main = document.getElementById("main");
      sideBar.style.width = sideBar.style.width === "250px" ? '0' : '250px';
      main.style.marginLeft = main.style.marginLeft === "250px" ? '0' : '250px';
    
      }
    
    
    
    function collapseButton() {
    
      var coll = document.getElementsByClassName("dropdown");
      var i;
      for (i = 0; i < coll.length; i++) {
        coll[i].addEventListener("click", function () {
          this.classList.toggle("active");
          var content = this.nextElementSibling;
          if (content.style.maxHeight) {
            content.style.maxHeight = null;
          } else {
            content.style.maxHeight = content.scrollHeight + "px";
          }
        });
      }
    
    
    
     }
    
      addEventListener("load", collapseButton);
    

    addevntlistner can call your collapseButton function like above . But remember to remove the onclick statement in your html file as shown below.

    <button type="button" class="dropdown" >Projects</button>