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 trialThomas Del Chiaro
9,451 PointsI don't understand why chaining focus() and keyup() is actually working
Hi everyone!
I don't understand why chaining is actually working. I was thinking that the "keyup" event handler, chained like this, should only be triggered when the "focus" is. We saw in the first part of the video that we had to re-focus to trigger the focus event handler.
$("#password").focus(passwordEvent).keyup(passwordEvent);
Can somebody explain?
Thanks
2 Answers
Dan Garrison
22,457 PointsjQuery allows you to chain some methods together. focus() takes a function as an input and will run that function when the user brings focus to the selected element. Like clicking in a text box for example. However, this method will only run once per focus. So if you need to execute the function again, you need to bring focus to the selected text box.
That's where the keyup() method comes in handy. It also takes a function as an input, but it only runs that function when the user stops typing. So in the chaining example the user first brings focus to the password box. The function specified will then run. When the user stops typing the keyup() method is triggered and the specified function is run again. It's important to note that you do not have to chain these methods together. You could also do the following and still have the code work the same. It's just more code.
$("#password").focus(passwordEvent);
$("#password").keyup(passwordEvent);
Ian VanSchooten
3,549 PointsSo, if I understand correctly, the focus()
method only runs once but it returns the jQuery object $("#password")
which means effectively after the focus event is fired and the method is run, we end up with $("#password").keyup(passwordEvent);