javascripthtmltoggle

HTML Buttons to make a show button act as a hide button as well as a show button


If you have a show button that when clicked shows a picture, how would you then make that button also act as a hide button to show the original picture like a hide reset sort of thing. below is my button code with the JS to go with it.

<button class="button" onclick="ShowPyramid()">Show Pyramid</button>
function ShowPyramid() {
  var elements = document.querySelectorAll('.triangle');
  elements.forEach(function (element) {
    element.classList.toggle('hidden');
  });    
}

Solution

  • The classList.toggle will already toggle the class, to hide and show the Pyramids.

    You could use event.target to change the text of the button so the user will know it toggles the visibility.

    function ToggleShowPyramid(event) {
        var elements = document.querySelectorAll('.triangle');
        event.target.innerHTML = event.target.innerHTML.startsWith('Show')
          ? 'Hide pyramid'
          : 'Show pyramid';
          
        elements.forEach(function (element) {
            element.classList.toggle('hidden');
        });    
    }
    .hidden {
        display: none;
    }
    <button class="button" onclick="ToggleShowPyramid(event)">Show Pyramid</button>
    <div class='triangle hidden'>Pyramid #1</div>
    <div class='triangle hidden'>Pyramid #2</div>