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 trialseema yadav
Courses Plus Student 345 PointsI am having a problem in understanding where to place '$' in front of the code.
var $overlay = $('<div id="overlay">saa</div>'); var $caption = $("<p></p>"); var $image = $("<img >");
$overlay.append($image); $overlay.append($caption); $( "body" ).append( $overlay );
$( "#imageGallery li a" ).click(function() { event.preventDefault(); var imageLocation = $(this).attr( "href" ); console.log(imageLocation); var imageCaption = $(this).children("img").attr("alt"); console.log(imageCaption); $image.attr("src", imageLocation); $caption.text(imageCaption);
$overlay.show(); });
$("#overlay").click(function(){ $overlay.hide(); });
For example when image and caption were appended to the body then no dollar sign is added before the code except for the one used for defining the variable, $overlay.append($image);
But when we appended overlay to body then $ was placed before the code. $( "body" ).append( $overlay );
Why in the first example dollar is added before it like- $$overlay.append($image);
2 Answers
Fernando Boza
25,384 PointsHi Seema remember that JQuery uses $ to know what element in the html or js file you want to modify.
Functions like append, next or attr, etc wouldn't need to add the $ because they are functions that change / modify the html and js elements, and we use the $ to specify which elements.
Jacob Mishkin
23,118 PointsThe $ sign used in front of your code is to denote jQuery. What is happening is that by using the $ sign jQuery is searching the DOM to find the element that you are requesting, then if found creates a new jQuery object for that element.
exmp:
$("#overlay").click(function(){ //the $("#overlay") is being searched in the DOM
$overlay.hide(); // if found creates the Jquery object here
});
if you would like to learn more check out this great reference jQuery