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 triallionelsurmont
7,092 PointsWhy can't this work properly with a named function?
Instead of writing this bit of code with an anonymous function:
$(".spoiler button").click(function() { $(".spoiler span").show(); } );
...why can't i write the same code with a named showfunction():
function showfunction() { $(".spoiler span").show(); }
$(".spoiler button").click(showfunction());
This doesn't produce the same result and when I preview it i see both the text and the button at the same time. It acts like I've already clicked the button in first scenario.
2 Answers
Steven Parker
231,275 PointsIt seems "already clicked" because you're calling your function when you set the click handler.
Try passing the function to the handler but not calling it:
$(".spoiler button").click(showfunction);
(I re-posted this as an answer, I accidentally posted it as a comment before)
lionelsurmont
7,092 PointsThanks. Fixed it ! :)