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

How to pass an argument to an event handler?

Hello everybody!

Help me, please. Is there a way to pass an argument to an event handler? Here is an example:

function printSmth(text) { console.log(text); }; $password.focus(printSmth('Hello World'));

?

The above code executes the function right away, so can it be overcome?

Thanks!

Hello Nikolay,

I'm not quite sure what you mean. If you have the following function:

function printSmth(text) { 
    console.log(text); 
}; 

$password.focus(printSmth('Hello World'));

then the function should run when you focus on the $password. Could you elaborate a bit more please?

Thanks for the reply. Yes, I meant that :) But because of the brackets on the event handler, the console prints out the text immediately after the page's loaded. And I can't figure out how to prevent this behavior..

1 Answer

Hi Nikolay,

The reason your function is failing is because you're not assigning a function to focus; you're assigning the result of the execution of printSmth()

What you should be doing is this:

function printSmth(text) { 
    console.log(text); 
}

$password.focus(function() { printSmth('Hello World');} );

// expanded version with explanation

$password.focus(function() { // state that we are running a function on focus
    printSmth('Hello World'); // actually run the function
});

That should work!

Also, for best practise, don't put a semicolon after functions declared the 'classical' way. Only place a semicolon after variable-declared functions: http://stackoverflow.com/questions/1834642/why-should-i-use-a-semicolon-after-every-function-in-javascript

Thanks for helping :) As I stated above, the issue is that this function executes once the page's loaded (because of the brackets)

Nikolay Komolov Ah I see, just updated the function for you ;)

Cool, how could I have not thought about this..?)) Thanks a lot!)

Thanks, a great explanation to a good question :)