skip to Main Content

I have a button at the bottom of my page that I hide and unhide by setting its style to display:none and display:block respectively. I do this with many objects multiple times throughout my code, so I use the following function:

function objectHide(object, hide) {
  if (hide == 'hide') {
  document.getElementById(object).style.display = "none";
  }
  else if (hide == 'unhide') {
  document.getElementById(object).style.display = "block";
  }
}

Once the button has been hidden and unhidden once it is no longer aligned to the center of the page and defaults to the standard left side.

Text-align center is attached to the body, but I have also tried attaching it to the button’s parent div, both in CSS and in Javascript after it is unhidden. None of these have worked and it continues to change back to the standard left side.

3

Answers


  1. If you really need to use .display for this then you’ll have to set the style property again when unhiding. Otherwise, you can toggling the .visibility property of your UI element. This should accomplish what you’re trying to achieve here.

    I hope this helps.

    Login or Signup to reply.
  2. It’s better to put the hide function in the button’s parent element. Something like this:

    HTML

    <div id="btn-container>
    <button>Click here</button>
    </div>
    

    CSS:

    #btn-container{
    display: flex;
    justify-content: center;
    }
    

    For the JavaScript:

    let btn = document.querySelector("#btn-container")
    if (btn.style.display === "flex") {
    btn.style.display = "none"
    }else{
    btn.style.display = "flex"
    }
    
    Login or Signup to reply.
  3. From the MDN See Also section for initial:

    • Use the revert keyword to reset a property to the value established by the user-agent stylesheet (or by user styles, if any exist)

    Using revert means you don’t have to determine what an element’s display attribute should be to re-display the item.

    "use strict";
    hide.onclick=()=>btn.style.display="none";
    show.onclick=()=>btn.style.display="revert";
    .container {
      text-align: center;
      padding: 1rem;
      border: thin solid grey;
    }
    <div class="container">
        <button type="button" id="btn">Centered Button</button>
    </div>
    <button type="button" id="hide">Hide</button>
    <button type="button" id="show">Show</button>

    Note the code snippet techniques of using the variables created for element ids is for brevity and not recommended in production (they may be shadowed by global variables or functions of the same name).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search