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 trialNikolay Komolov
23,033 PointsHow 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!
Nikolay Komolov
23,033 PointsThanks 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
Louis Otto
23,264 PointsHi 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
Nikolay Komolov
23,033 PointsThanks for helping :) As I stated above, the issue is that this function executes once the page's loaded (because of the brackets)
Louis Otto
23,264 PointsNikolay Komolov Ah I see, just updated the function for you ;)
Nikolay Komolov
23,033 PointsCool, how could I have not thought about this..?)) Thanks a lot!)
Peter Tomasiewicz
5,592 PointsThanks, a great explanation to a good question :)
John Coolidge
12,614 PointsJohn Coolidge
12,614 PointsHello Nikolay,
I'm not quite sure what you mean. If you have the following function:
then the function should run when you focus on the $password. Could you elaborate a bit more please?