views:

99

answers:

2

We have, like everyone else, forms all over our web app.

So far we've been using the following (or some variation) in most every form element:

class="formThingy"    
onFocus="document.theForm.theField.className='formThingySelected';" 
onBlur="document.theForm.theField.className='formThingy';"

It's a pain. Is there an easy way to do get the same result with either javascript/jQuery or CSS?

I know in css we can use things like :hover but that doesn't get what we're looking for.

My guess is that there is something we can do with jQuery that looks at everything with a class of 'FormThingy" and changes it onFocus and back onBlur, I'm just not sure where to start.

+1  A: 

Using jQuery you could accomplish the same thing with:

$('input').focus(function() {
    $(this).attr('class', 'formThingySelected');
}).blur(function() {
    $(this).attr('class', 'formThingy');
});

You might want to adjust the selector for better performance. The selector should match all elements you wish to attach the focus/blur behavior to.

Ken Browning
So, if I wanted to do this to all <input> and <select> tags I would have to add this in twice? Really, I only want this bot <input>, <select> and <textarea>.
Jason
then an appropriate selector would then be `'input, select, textarea'`
Ken Browning
So I have to ask...is there a performance difference between your answer and Alex's or is the difference just a matter of style?
Jason
I would say the use of `.formThingy` as a selector over tag names would be slightly more performant. Also, using jQuery's native class manipulation methods over `attr` is more flexible as it won't overwrite other class names. More importantly though, I win at golf :)
Alex Barrett
I'm not 100% confident about this, but I seem to recall selectors against tags take advantage of browser apis to get elements by tag. Some best-practices recommend prepending .class selectors whenever possible. If you only want to apply it to input elements of `formThingy` then my money is on $('input.formThingy') outperforming $('.formThingy').
Ken Browning
You can try it, but I also have my doubts. Aside from the fact that modern browsers implement the `getElementsByClassName()` method, combining the two selectors forces jQuery to do more work. But as always, the only way to find out is to run benchmarks. Also, this is a prime example of premature optimization.
Alex Barrett
@alex: yes, its definitely that
Ken Browning
+1  A: 
$('.formThingy').bind('focus blur', function() {
    $(this).toggleClass('formThingy formThingySelected');
});
Alex Barrett
blur and focus are currently unsupported by `live` :(
Ken Browning
Wow, you're right. I had forgotten that! In that case I recommend the first version :)
Alex Barrett
Jason