Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript jQuery Basics Understanding jQuery Events and DOM Traversal What is Traversal?

Dimitris Karatsoulas
Dimitris Karatsoulas
5,788 Points

How to have one spoiler revealed max at any given time. [DUPLICATE]

So, I've been thinking that it would be a nice feature if with every next button click the previous spoiler would return to hidden, that way at any given time only one spoiler will be shown. I've been working towards this idea but with no success so far. Any ideas?

This is what I have done so far:

const $button = $('<button>Reveal Spoiler</button>');
//Append to web page
$('.spoiler').append($button);
//Hide spoiler text
$('.spoiler>span').hide();

$('.spoiler').on('click ', 'button',  function (e) {
    //Show the spoiler text
    hideSpoilers();   
    $(this).prev().show();
    //$('.spoiler>span').show();
    //Hide the "Reveal Spoiler" button
    //$(this).hide();

});

function hideSpoilers() {
    const $buttons = $('button');

    for (let item of $buttons) {
       $('.spoiler>span').hide();
    } 
 }

Please note that I have yet to understand how to make a function in jQuery. As about my code:

  1. As it is right now it does reveal just one spoiler at the time but the button remains visible. I'm trying to hide it.
  2. If the $(this).hide(); is active it hides the buttons for good, they're not visible till I refresh and the page resets.
Steven Parker
Steven Parker
218,814 Points

This looks like a duplicate of your other question, see the answer(s) posted there.
You can delete it while it has no answers by clicking on the small rectangle with the 3 dots and choosing "Delete Question".