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

Jacob Bender
Jacob Bender
15,300 Points

Help with jquery

So, I am following along with the tutorials, and on the star wars spoiler part I have

var spoilerOn = false;
$(".spoiler span").hide();
if (spoilerOn === false)
{

  $(".spoiler").append("<button>Reveal Spoiler!</button>");
  $("button").click(function(){

    $(".spoiler span").show();
    $( "button" ).animate({
      marginTop: "0.5in",
    },500 );
    });
  spoilerOn = true;
}

but when I try to add functionality to hide it, it ceases to work. I figured it would be something like

if (spoilerOn === true)
{

  $(".spoiler").append("<button>Hide Spoiler!</button>");
  $("button").click(function(){
    $(".spoiler span").hide();
    $( "button" ).animate({
      marginTop: "-0.5in",
    },500 );
    });
  spoilerOn = false;
}

But alas this does not work. What am I doing wrong? I set the condition to true, so shouldn't it work based on what my spoilerOn bool is set to?

Thank you.

Jacob Bender
Jacob Bender
15,300 Points

Not sure why my code isn't formatting correctly..... I used [code][/code] tags...

Jacob I fixed the formatting for you, for proper formatting refer to the Markdown Cheatsheet, it's pretty simple, basically wrap your code in (```) at the beginning and end without the parenthesis.

Jacob Bender
Jacob Bender
15,300 Points

Thank you mikes02. Don't suppose you know the answer as well? :)

1 Answer

you add the button dynamically to the DOM, so accessing the 'button' with this won't work $("button").click(action)

you should try accessing it with Jquery's '.on' method. something like this:

$(".spoiler").on('click', 'button', function(){ $(".spoiler span").hide(); $( "button" ).animate({ marginTop: "-0.5in", },500 );});

Jacob Bender
Jacob Bender
15,300 Points

Thank you. I figured it had to do with the fact I was adding the button in code. Cheers.