0

I'm working on a website project for school. Currently I'm attempting to create a quiz with question and answers. I want the answers to be hidden and shown by buttons. At the moment I'm using a script the user "dimitryous" once uploaded.

I know that only one buttons works because the script uses ids and not classes. I'd like to change that but I have no idea how... Could you guys please help me out?

var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
var show_button = 'Show', hide_button = 'Hide';
function showhide() {
    var div = document.getElementById( "hide_show" );
    var showhide = document.getElementById( "showhide" );
    if ( div.style.display !== "none" ) {
        div.style.display = "none";
        button = show_button;
        showhide.innerHTML = button_beg + button + button_end;
    } else {
        div.style.display = "block";
        button = hide_button;
        showhide.innerHTML = button_beg + button + button_end;
    }
}
function setup_button( status ) {
    if ( status == 'Show' ) {
        button = hide_button;
    } else {
        button = show_button;
    }
    var showhide = document.getElementById( "showhide" );
    showhide.innerHTML = button_beg + button + button_end;
}
window.onload = function () {
    setup_button( 'hide' );
    showhide(); // if setup_button is set to 'show' comment this line
}

1 Answer 1

1

var buttons = document.querySelectorAll('.hide-show');
buttons.forEach(function (button) {
  button.onclick = function () {
    var content = this.parentNode.getElementsByTagName('span')[0];
    if (content.style.display !== 'none') {
      content.style.display = 'none';
      this.textContent = 'show';
    } else {
      content.style.display = 'inline';
      this.textContent = 'hide';
    }
  }
})
<div>
  <button class="hide-show">hide</button>
  <span>Content... 1</span>
</div>

<div>
  <button class="hide-show">hide</button>
  <span>Content... 2</span>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

This works in the "Run code snippet" but not in my website. Furthermore the content needs to be hidden on load.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.