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 Simple Lightbox Perform: Part 2

Steve Fan
Steve Fan
8,218 Points

Why we need to use $('<div id="overlay"></div>') but not '<div id="overlay"></div>'.

In the video, the instructor set: var overlay = $('<div id="overlay"></div>');

But what we need to fill in the "append()" is: '<div id="overlay"></div>'

So why he use $('<div id="overlay"></div>') but not '<div id="overlay"></div>'

And what $() really do in this command?

Could someone help me to explain this please.

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

append() can take a variety of arguments, including string, HTMLand jQuery object. $('<div id="overlay"></div>') turns the HTML into a jQuery object. I'd have to check the code for the project to be certain, but I'm fairly sure you'll be using overlay again later in the code and that's why it's stored in a variable/jQuery object.

Steve Fan
Steve Fan
8,218 Points

Thanks, Seth K. I get it now. Could I ask you one more question? Why we cannot use normal variables such as "overlay" or "image" But we have to use jQuery objects such as "$overlay", "$image" all the time?

Is there any advantage when using jQuery objects?

Seth Kroger
Seth Kroger
56,413 Points

Beginning a variable name with "$" when it's supposed to be a jQuery object is just a stylistic convention and doesn't necessarily have to be followed.

Steve Fan
Steve Fan
8,218 Points

So you mean we also can just leave the variables alone and use it like normal. Everything still stay the same, isn't it?

Steve Fan
Steve Fan
8,218 Points

I just checked it. Without $, when I try to run the webpages, It noticed something in console like: overlay.append(image); is not a function //I took off all $ in the js file

I doubt that $ have to be appear all the time or I just get lost?