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?

Nate Baker
Nate Baker
17,247 Points

prev() method does not display spoiler text, but next() method does.

When implementing the prev() method, only the button NOT clicked will stay displaying. The button clicked goes away. When implementing the next() method, however, behavior is as expected.

2 Answers

John Bastian Bolhano
John Bastian Bolhano
4,800 Points

Probably your button was added before the spoiler span like this. Try changing the prepend to append then use prev(), see if it works

const $button = $("<button>Reveal Spoiler</button>");

$(".spoiler").prepend($button);
Alan McClenaghan
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alan McClenaghan
Full Stack JavaScript Techdegree Graduate 56,501 Points

Exactly. if you used the append() method then you use prev(), while If you kept the prepend() method from the earlier video then you need to use next()

Thanks for the tip Alan. I tried both combos- append()/prev() and prepend()/next(), which both leave me with the same outcome- both spoilers are revealed when only one is clicked. I changed the 'event.target' to 'this' but same outcome. I've reviewed the code line by line in comparison with the video, and it appears identical to the video however I cannot get the clicked upon spoiler to reveal only itself, without revealing the 2nd spoiler as well. Below is my code, if anyone has a recommendation on what needs to change I'd appreciate the help.

$('.spoiler').on('click', 'button', function(event) {
  console.log(event.target);
  // Show spoiler text
  $(event.target).prev().show();
  // Hide the reveal spoiler button
  $(event.target).hide();
});  

// Create the "Reveal Spoiler" button
const $button = $('<button>Reveal Spoiler</button>');
// Append to web page
$('.spoiler').append($button);
// Hide spoiler on page load
$('.spoiler span').hide();
// When button is pressed 
$('.spoiler button').on('click', function(){
  // Show spoiler
  $('.spoiler span').show();
  // Hide the reveal spoiler button
  $('.spoiler button').hide();
});