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 trialJacob Bender
15,300 PointsHelp 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.
mikes02
Courses Plus Student 16,968 PointsJacob 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
15,300 PointsThank you mikes02. Don't suppose you know the answer as well? :)
1 Answer
ifedapo olarewaju
4,386 Pointsyou 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
15,300 PointsThank you. I figured it had to do with the fact I was adding the button in code. Cheers.
Jacob Bender
15,300 PointsJacob Bender
15,300 PointsNot sure why my code isn't formatting correctly..... I used [code][/code] tags...