Home > Net >  Save a variable number of CSS styles as a JS variable for show/hide?
Save a variable number of CSS styles as a JS variable for show/hide?

Time:03-15

Let me preface by saying I don't have a ton of Javascript experience. I have a CSS class specifically used to show/hide things with a button click on my site. The progress bars are shown by default, and have their various colors and styles shown no problem. Using the following code, the button will hide the progress bars correctly.

    function showhide() {
    var x = document.getElementsByClassName("showhideclass");
    var i;
    for (i = 0; i < x.length; i   ) {
      if (x[i].style.display === "none") {
        x[i].style.display = "block";
      } else {
        x[i].style.display = "none";
      }
    }
  }

However, when the button is clicked again to show the progress bars again, the color and other styling does not show up. I know this is because of the line x[i].style.display = "block"; but I do not know how to save the CSS styling as a variable in this function to have it reapplied on "Show" click. I've tried the following code, and it will still hide the progress bars properly, but it does not display them again on second click.

function showhide() {
    var x = document.getElementsByClassName("showhideclass");
    var i;
    for (i = 0; i < x.length; i   ) {
      var elstyle = window.getComputedStyle(x[i]);
      if (x[i].style.display === "none") {
        x[i].style.display = elstyle;
      } else {
        x[i].style.display = "none";
      }
    }
  }

I'm not quite sure what I'm missing here, does anyone have suggestions?

CodePudding user response:

Maybe you want to use something like this.

Define some css class with a display: none property and toggle the class on the elements itself via button-press. All properties such as display: flex, display: block, or display: none will not be overwritten.

function showhide() {
  const elements = document.getElementsByClassName("showhideclass");
  [...elements].forEach(e => e.classList.toggle("hidden"));
}
.hidden {
  display: none;
}
<p >1</p>
<p >2</p>
<p >3</p>
<p >4</p>
<button onclick="showhide()">Toggle</button>

CodePudding user response:

@jns had the right of it. The following code works perfectly as intended, with the styles being saved for each progress bar as it is hidden and shown.

  function showhide() {
    var x = document.getElementsByClassName("showhideclass");
    var i;
    for (i = 0; i < x.length; i   ) {
      var elstyle = window.getComputedStyle(x[i]);
      if (x[i].style.display === "none") {
        x[i].style = elstyle;
        //x[i].style.display = "block";
      } else {
        x[i].style.display = "none";
      }
    }
  }
  • Related