The div is supposed to be hidden

Question:
In my game, when the player switches to a different screen, the screen that they are on should be hidden. This happens when switching from the start screen to a different screen, but not when they switch between the help and spaceship screens. What is wrong?
Repl link: @element1010/Cosmic-Adventure

<div id="start">...</div>
<div id="spaceship">...</div>
<div id="help">...</div>
let currentScreen = "start";

function go(screen) {
  document.getElementById(currentScreen).hidden = true;
  document.getElementById(screen).hidden = false;
  document.getElementById(`${screen}-navbutton`).addClass("selected");
  document.getElementById(`${currentScreen}-navbutton`).removeClass("selected");

  currentScreen = screen;
}

I traced the issue to two things:

  1. .addClass and .removeClass: Instead, use .classList.add or .classList.remove
  2. The suffix -navbutton will not work, as no elements have the -navbutton ending

So, the fixed JS code would be:

let currentScreen = "start";

function go(screen) {
  document.getElementById(currentScreen).hidden = true;
  document.getElementById(screen).hidden = false;
  document.getElementById(`${screen}`).classList.add("selected");
  document.getElementById(`${currentScreen}`).classList.remove("selected");

  currentScreen = screen;
}

Then, in the devtool console, you can type go('help') and it will change to the help page.

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.