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
kabir k
Courses Plus Student 18,036 PointsWhy is '$(this)' used in the passwordEvent function?
In the passwordEvent function, why are we using '$(this)' even when we have not referenced the password input element, #password, yet?
Here's the function:
function passwordEvent(){
//Find out if password is valid
if($(this).val().length > 8) {
//Hide hint if valid
$(this).next().hide();
} else {
//else show hint
$(this).next().show();
}
}
//When event happens on password input
$("#password").focus(passwordEvent).keyup(passwordEvent);
1 Answer
Marcus Parsons
15,719 PointsHey Kabir,
When the event handlers of "focus" and "keyup" call the function passwordEvent on the object $("#password"), the $(this) object becomes a reference to $("#password") because that password object is the object that called that function. When an event handler utilizes the "this" keyword, it is always a reference to the specific element or object that called it.
You'll more often see the "this" object used in cases where there can be multiple versions of the same element such as targeting a specific list item to do an action in an unordered list. Here's an example I made of targeting specific list items where you can click on a list item and it will show that specific list item's text content: http://codepen.io/anon/pen/PqWJdV