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 Password Confirmation Form Perform: Part 1

Oğulcan Girginc
Oğulcan Girginc
24,848 Points

How does $(this) is linked to $("#password")?

How come this keyword knows that it is linked to #password, since the function that has this keyword was written before the #password?

$('form span').hide();

function passwordEvent(){
  if($(this).val().length > 8) {    
     $(this).next().hide();
  } else {   
     $(this).next().show();
    }
}

$('#password').focus(passwordEvent).keyup(passwordEvent);

2 Answers

Jorge Septien
Jorge Septien
20,339 Points

You are binding the passwordEvent handler to the focus and keyup events on the #password element. The this keyword always refers to the owner of the method, in this case the selected #password element. The code in the handler will only run when the events are triggered.

I recommend reading up on JavaScript hoisting, scope, and context. This will explain what is happening above. A good set of videos i recommend can be found here: https://www.youtube.com/channel/UCVTlvUkGslCV_h-nSAId8Sw just check out the javascript section, he does a very good job explaining.