Search code examples
javascriptif-statementstylesdisplay

"style.display = 'flex/none'" not working


So I thought it would be pretty simple to implement an if statement to have an element appear or disappear at the click of a button. After a couple of hours now, I have not gotten further than getting the element to disappear. It registers the second click(tested with a console.log), but the display property does not change back to 'flex'.

I've also already tried different variations of 'getElementById' and 'querySelector' during my sentence.

const edit = document.getElementById('edit-btn');
const fill = document.querySelector('#filler');

edit.addEventListener('click', popInOut(fill))

function popInOut(e){
    if(e.style.display=='flex'){
        e.style.display='none'
    }else if(e.style.display=='none'){
        e.style.display='flex'
    }
}

The 'filler' element is a bootstrap column with this styling.

#filler{
    display:flex;
    flex-direction: column;
    background-color: #1c1f22;
    position:absolute;
    top:40%;
    height:50%;
}

Solution

  • hey it is your query selector which is causing the problem and also you can use your filler directly in function because its declared in global scope

       const edit = document.getElementById("edit-btn");
       const filler = document.getElementById("filler");
        
        
        edit.addEventListener("click", fix);
        
        function fix() {
          if (filler.style.display === "none") {
            filler.style.display = "flex";
          } else {
            filler.style.display = "none";
          }
        }
    body {
      font-family: sans-serif;
    }
    
    #filler {
      display: flex;
      /* flex-direction: column; */
      background-color: whitesmoke;
      position: absolute;
      top: 30%;
      left: 20%;
      height: 50%;
      gap: 1rem;
    }
    
    #filler div:nth-child(even) {
      background: turquoise;
    }
    
    #filler div:nth-child(odd) {
      background: yellowgreen;
    }
    <!DOCTYPE html>
    <html>
      <head>
        <title>Parcel Sandbox</title>
        <meta charset="UTF-8" />
        <link href="style.css"/>
      </head>
    
      <body>
        <div id="app">
          <div id="filler">
            <div>Hare krishna</div>
            <div>Radhe Shyam</div>
            <div>Sita Ram</div>
          </div>
          <button id="edit-btn">Edit</button>
        </div>
    
        <script src="index.js"></script>
      </body>
    </html>