0

The HiddenUI as well as the HiddenElements are supposed to be displayed when pressing Enter.

That works but only on the second time I'm pressing "Enter". The first time the if-statement in my toggleHiddenElements function skips the the first if statement and jumps straight to else. (checked with debugger).

But it does work as intended the second time I press enter.

/*toggle view hiddenUI and hidden elements*/

function toggleHiddenElements() {
  let HiddenUI = document.getElementById("hiddenUI");
  let HiddenElements = document.getElementsByClassName("deactivated");
  if (HiddenUI.style.display == "none") { /*jumps to else the first time I press Enter
    HiddenUI.style.display = "block";
    for (let i = 0; i < HiddenElements.length; i++) {
      HiddenElements[i].style.display = "block";
    }
  } else {
    HiddenUI.style.display = "none";
    for (let j = 0; j < HiddenElements.length; j++) {
      HiddenElements[j].style.display = "none";

    }
  }
}


/* EventListener for "Enter" Keybind */

document.addEventListener("keydown", (e) => {
  if (e.code == "Enter") {
    e.preventDefault();
    toggleHiddenElements();
  }
});

Full code can be found here

lostinjs
  • 40
  • 6
  • 2
    Please add a [mcve] (with the focus on _minimal_) that shows the actual problem _in the question itself_ – Andreas Oct 26 '20 at 16:27
  • 2
    The `style` object attached to an element node will not show you styles driven by CSS (or by simple default). – Pointy Oct 26 '20 at 16:29
  • Does this answer your question? [why are initial CSS styles not visible on DOM element .style field?](https://stackoverflow.com/questions/54321532/why-are-initial-css-styles-not-visible-on-dom-element-style-field) – AndrewL64 Aug 28 '21 at 14:46

1 Answers1

2

The HTMLElement.style property only represents the CSS declarations set in the element's inline style attribute, so the first time toggleHiddenElements() runs, HiddenUI.style.display is an empty string.

To fix your code, you can use window.getComputedStyle() to initially get the styles you set in CSS:

if (window.getComputedStyle(HiddenUI).display == "none") {
  HiddenUI.style.display = "block";
  for (let i = 0; i < HiddenElements.length; i++) {
    HiddenElements[i].style.display = "block";
  }
} else {
  HiddenUI.style.display = "none";
  for (let j = 0; j < HiddenElements.length; j++) {
    HiddenElements[j].style.display = "none";
  }
}

More info: why are initial CSS styles not visible on DOM element .style field?

adamgy
  • 4,543
  • 3
  • 16
  • 31