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 trialTIAGO SANTOS
2,450 PointsWhy can't I add event to the appended button?
I was trying to add event handler right after appending the button to the DOM but didn't work. Why? I thought since jquery returns the object i am selecting or appending this would work and spare me a few lines of code.
He is what i tried to do:
$(".spoiler").append("<button>Reveal spoiler!</button>").click(
function(){
$this.css("background-color","black");
}
);
here is the snapshot of my workspace: https://w.trhou.se/m3xme6um3b.
1 Answer
Brett Connolly
12,874 PointsYou're appending the click event to the 'spoiler' class element, not the button itself, in this scenario. jQuery will chain continual method calls to the original selector, in your case $(".spoiler"), unless you use something like .find() before doing further calls. Didn't know you could actually chain .find(), after an append, to apply methods to the appended elements. Years later and still learning new stuff about jQuery.
//Full Chaining
$(".spoiler").append("<button id='thisButton'>Click Me</button>").find("#thisButton").on("click", function(){
$(this).css('background-color', 'black');
});
//The way I would do it (cleaner code and separation of functionality)
$(".spoiler").append("<button id='thisButton'>Click Me</button>");
$("#thisButton").on("click", function(){
$(this).css("background-color", "black");
});