Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
231,126 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".