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!

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

Creating a spoiler revealer

Hi. I've made a page with 3 articles. They each have buttons on them so that when the user clicks on 'read more', it reveals more of the article, like in the spoiler revealer exercise. I got it to work, but I have a question about it.

In my app.js file, my code is this

var $button = ("<button>Read More</button>");

$("span").hide();

$(".primary-content").append($button);
$(".secondary-content").append($button);
$(".extra-content").append($button);

$("button").click(function(){

  $(this).prev().show();
  $(this).remove();

});

what I don't understand is that, when I put

$("button").click(function()…

it works, but when I put

$button.click(function()…

it didn't work. I'm not sure why not. Could someone explain this to me? Thanks.

2 Answers

Sreng Hong
Sreng Hong
15,083 Points

Hi Robin

Here is a jQuery click() Method:

$(selector).click(function)

So, I think the $button.click(function()… doesn't work because

$button = ("<button>Read More</button>") is not a selector, it's an html element

but `$("button") is a selector of button tags

Feel free to correct me if i'm wrong. Good luck

Thanks Sreng