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

Jonathan Jackson
Jonathan Jackson
2,716 Points

I simply need a second description of what's going on in this video. It's just not working for me. Can someone help?

This is my .js for this:

 $(".spoiler span").hide();
 $(".spoiler").append("<button>Reveal Spoiler!</button>");
 $(".spoiler").click(
      function() {
           "use strict";
           $(this).prev().show();
           $(this).prev().remove();
 }
 )

But when I preview that, it does all sorts of weird stuff. Depending on how I change it, it'll delete the death star, it'll do nothing, it'll never show the spans, etc. Nothing about what he's saying seems to be working for me, even though I'm using the exact same code for the exception of the "use strict" statement.

Please someone tell me how I'm doing this wrong.

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

Currently you are attaching a click handler to the entire spoiler paragraph and not just the button you added. Because the click() method considers "this" to be the paragraph, you're telling it to show/hide what immediately precedes it, which happens to be the Death Star graphic for the first spoiler and the previous spoiler for all the rest.

What you should be doing is add a click function to the buttons. The click function then selects the element that precedes it (the span with the spoiler), show it, then remove itself (the button). The code should look like:

$("button").click(function() {
    $(this).prev().show();
    $(this).remove();
});

I know you posted this six months ago but thank you anyways because this explanation was exactly what I needed