Search code examples
javascripthtmlcssdomevent-listener

Javascript code doesn't fire until the 2nd click for an html button?


I'm learning javascript, and this simple piece of code just won't work the way I need it to.

All I need is to display the main tag at the click of a button. HOWEVER, it doesn't want to display until the SECOND click.

So the first click doesn't display the main. The second click does.

I've tried moving my coding around the html document (before/after body closing tag, etc).

I've looked through stack overflow, and similar questions don't really help my case. Or at least I don't understand how they can help me as a beginner.

var aboutShow = document.getElementById("aboutLink");
aboutShow.addEventListener("click", displayMain);

function displayMain(){
  var mainSection = document.getElementsByTagName("main")[0];
  if (mainSection.style.display === "none"){
    mainSection.style.display = "grid";
  }
  else{
    mainSection.style.display = "none";
  }
}
main{display:none;}
<main> ... </main>
<button type="button" id="aboutLink">About</button>

There has to be something I'm missing that prevents that 1st click from firing the code. I mean, it seems simple enough???


Solution

  • var aboutShow = document.getElementById("aboutLink");
    aboutShow.addEventListener("click", displayMain);
    
    function displayMain(){
      var mainSection = document.getElementsByTagName("main")[0];
      if (mainSection.style.display || "none" === "none"){
        mainSection.style.display = "grid";
      }
      else{
        mainSection.style.display = "none";
      }
    }
    main{display:none;}
    <main>text</main>
    <button type="button" id="aboutLink">About</button>

    Initially mainSection.style.display is empty, so it falls on the else part of the if statement and changes the property to none. On the second click, the property now has the value of none, that's why it works on the second click.

    The HTMLElement.style property is used to get as well as set the inline style of an element.