Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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???

like image 335
Catherine Hill Hyman Avatar asked Sep 19 '26 00:09

Catherine Hill Hyman


1 Answers

if (mainSection.style.display === "none") is looking for an inline style tag, so instead of setting display:none; in your CSS, just set it inline on the element:

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 style="display:none;"> ... </main>
<button type="button" id="aboutLink">About</button>
like image 68
APAD1 Avatar answered Sep 20 '26 14:09

APAD1