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 (2014) Creating a Spoiler Revealer Perform: Part 3

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

I wrote the code a different way, which uses only 2 semicolons. Is there anything stylistically wrong with it?

My code works the same way the code in the video does; it's just structured such that it's a single statement, and the function within the click function is a single statement.

$(".spoiler span").hide()
                  .after("<button>CLICK TO SEE SPOILERS!</button>")
                  .next()
                  .click(function() {
                    $(this).prev()
                           .show()
                           .next()
                           .remove();
                  });

2 Answers

Luis Padron
Luis Padron
397 Points

I wouldn't needlessly chain methods/functions like you have done. It makes reading code a lot more difficult than it needs to be, and just adding a comment doesn't fix the issue you might have where some other user changes the HTML and breaks your script. They then have to go and fix the JS as well as the HTML.

A famous quote says: "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability."

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

Thanks for your input! I have never heard that quote before, but I'll be sure to keep it in mind. (:

Steven Parker
Steven Parker
229,732 Points

That's kind of clever. :+1: I tend to do similar things in code myself.

Probably the biggest risk in doing this is you are relying on the HTML structure instead of targeting the elements individually. Someone changing the HTML would break the script and perhaps not know why or how to fix it.

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

Thanks for your input! Would commenting the code to say what the code does and what it expects to see in the HTML fix that problem, or would it be better to restructure the code to make it more readable?