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 (2014) Creating a Spoiler Revealer Perfect

How can I do this?: When the user clicks the spoiler, everything goes back to its initial state

Hello!

I tried to add a new functionality to the project but I need some help! I want to be able to trigger a function when the spoiler is clicked, that function will restore the button and hide the spoiler, so everything will look like when we start.

I tried to do it and everything seems to be fine but the new button doesnΒ΄t work when you click on it. Even when is exactly the same html code as the initial button.

1 Answer

There are a lot of ways this can be done, but this follows in line with the video and your request:

//Prevent spoilerphobes from seeing spoilers
//Solution: Hide spoilers and reveal them through user interaction

//1, Hide spoiler
$(".spoiler span").hide();
//2, Add a button
$(".spoiler").append("<button>Reveal Spoiler!</button>");
//3, When button pressed
$("button").click(function(){
  //3.1, Show spoiler and add a click event
  $(this).prev().show().click(function(){
    // if the spoiler is clicked, hide it, and then show the button 
    // since the button is the next html element after the spoiler, we select it with .next()
    $(this).hide().next().show();
  });
  //3.2, Hide the button instead of removing it
  $(this).hide();
});

The reason the button was not working for you, I suspect, is that you were creating a new button without attaching a new jquery click event to it. When the code $("button").click() is run, only existing buttons have the event bound to them, new ones will not unless you reran that code or attached a new click event to a new button when creating it.

Hope this helps, and feel free to ask more questions if you have them! :D