Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading