Monday, December 6, 2010

Chaining jQuery Pseudoselectors

I just finished a very simple Javascript tweak to an app. Here was the requirement: "When the user opens our sign-in modal, we should focus the on the first input." Whatever code I wrote, I would put it a callback when the modal was finished opening.

This was my first solution: target the id of the first input, and focus on it.

$('input#user_email').focus();

But I didn't like that, because it's not very flexible. What if we add another input to the beginning of the form? We'd have to change the javascript, too.

After a little tinkering with jQuery's psuedoselectors, I came up with this:

$('#sign-in-modal-form').find('input:not(:hidden):first').focus();

Besides being more flexible to future changes, I think this is still pretty readable: select the first input that isn't hidden and focus on it.