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

Basic JQuery Question

Hello, I am new to team treehouse and new to Javascript. I am starting to get a grip on how to code with javascript, but I am confused with one part. I am confused when calling the .click(function() method and defining the variables. In the jquery beginner project I created the following code:

$(".order_now").click(function() {
        var $link = $(this)
        $link.next().show("slow");
        $link.remove();
        return false;
    });

Specifically, what I do not understand is this line: var $link = $(this) What is the significance of that line? I understand what the code is doing below that, but why are we calling out the link variable like that?

Thank you for your help!

2 Answers

The $(this) in jQuery refers to the element you are within in context to where it's being called. In this case it refers to the $(".order_now") link. It's a good idea to set it to a variable as you often use it more than once.

You'll get more into this soon if you continue to go through the jQuery tutorial.

Thanks for the quick response! So setting the links within the .order_now class to = $(this) is just because we are referring to it multiple times within that function? What would happen if I did not set the link as a variable?

If you just use $(this) without setting a variable everything is the same but it becomes less performant in longer code. If you have multiple items and you tried to access it with the $(".order_now") selector it would select all with that class and not just the one in relation to the link you clicked.