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

CSS jQuery Basics (2014) Creating a Simple Lightbox Perform: Part 4

Juan García
Juan García
10,723 Points

What's the point of using text(), when there is already a <p></p> appended to the image?

At the beginning we set

var $caption = $("<p></p>");

So what I tried inside the function within click() was something similar to what we used with the value of the image, that is:

$caption.attr("alt", captionText);

Of course, it didn't work. So I'm assuming that text() is just the method to use when setting the value of text, and with

var $caption = $("<p></p>");

we are just assigning an HTML selector to that value?

In addition, wouldn't it be better practice if we first got the alt attribute and set the caption, and then show the overlay? Or at least less confusing...

Thanks!

3 Answers

Sean T. Unwin
Sean T. Unwin
28,690 Points

Paragraph tags (p) don't have an attribute of alt so that's likely why it didn't work.

text() is a jQuery function that, when given an argument, sets the content of an element. So your assumption is correct. :)

we are just assigning an HTML selector to that value?

Correct. To be more specific, we are creating a new element (a paragraph, i.e. $caption) and then, after we append() it, we use the text() function to assign some content to that element ($caption).

In addition, wouldn't it be better practice if we first got the alt attribute and set the caption, and then show the overlay? Or at least less confusing...

If we did that we would have to declare the variable, captionText, outside of the scope of the click event, probably where $caption is declared. The big issue with doing this is that the captionText is dependent upon the image being clicked so it wouldn't work as there would be no context to assign it to. So while it may seem, at a glance, to be less confusing, we would not attain the goal that we wanted.

Excellent explanation, thank you

Excellent explanation, thank you

Excellent explanation, thank you

Ryan Atkins
Ryan Atkins
8,635 Points

So .text() is actually adding the text between the <p></p> that we had set prior when declaring the variable?

Thank for the clear answer, Sean. And of course thanks to Juan for asking the question. I was wondering about this. :)