[Solved] Javascript function to toggle menu items A, B, C, D [closed]


Use if statements and apply different styles or classes.

CSS

.hidden {
  display: none;
}

HTML & JavaScript

<div id="A" class="" onclick="handlePress('A');">A</div>
<div id="B" class="hidden" onclick="handlePress('B');">B</div>
<div id="C" class="hidden" onclick="handlePress('C');">C</div>
<div id="D" class="hidden" onclick="handlePress('D');">D</div>

<script type="text/javascript">
const letters = ['A', 'B', 'C', 'D'];

function handlePress(id) {
  document.getElementById(id).classList.remove('hidden');

  letters.forEach((letter) => {
    if (letter !== id) {
      document.getElementById(letter).classList.add('hidden');
    }
  });
}
</script>

solved Javascript function to toggle menu items A, B, C, D [closed]