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

CSS jQuery Basics (2014) Creating a Password Confirmation Form Perfect

Calling function "When event happens on password input"

I reallyed enjoy the project, it was hard but very useful and fun. My question is about calling a function.

My very elementary understanding of a function is that you have to call it with the two parenthesis. However, in this particular part of the code it is not and I really don't understand why:

//When event happens on password input

$password.focus(passwordEvent).keyup(passwordEvent).keyup(confirmPasswordEvent).keyup(enableSubmitEvent);

//When event happens on confirmation input

$confirmPassword.focus(confirmPasswordEvent).keyup(confirmPasswordEvent).keyup(enableSubmitEvent);

Again, my simple understanding would naturally write $password.focus(passwordEvent()) .........(etc).

1 Answer

Hi Frank,

Great question!

The jQuery focus method can accept what is called a 'callback' function. This function executes after focus() has finished running. To make this less abstract, consider that after you have someone's attention, you can then try to explain directions. In code, that might look like this:

<input type="text" id="attention">
// let's first make sure $attention is a jQuery object holding a reference to an HTML input tag with id='attention'
var $attention = $("input#attention");

function explainDirections() {
  // arbitrary directions
  alert('turn left, then turn right');
}

// after the #attention input field has focus, let's call a function that will alert some arbitrary directions
$attention.focus(explainDirections);

// this calls explainDirections before the #attention input field has focus
$attention.focus(explainDirections());

$attention.focus(explainDirections()) will first call explainDirections() and place the return value, if any, as the argument into $attention.focus().

jQuery's focus() will only accept a function or data and a function. The jargon they use is 'handler' for the function name to execute. From the above example, explainDirections is a function 'handler' that will handle how your program reacts when focus() is done executing.

If this made it more confusing, you have my sincere apologies. I completely understand how tricky it can be to grasp this.