views:

145

answers:

2

I have a such fuctions for Jquery:

$("input").focus(function () {
    $(this).addClass('focus');
});
$("input").blur(function () {
    $(this).removeClass('focus');
});

$("select").focus(function () {
    $(this).addClass('focus');
});
$("select").blur(function () {
    $(this).removeClass('focus');
});

$("textarea").focus(function () {
    $(this).addClass('focus');
});
$("textarea").blur(function () {
    $(this).removeClass('focus');
});

Is it possible to optimize, for a less code?

+8  A: 
$("input,select,textarea").focus(function() {$(this).toggleClass('focus')})
                          .blur(function() {$(this).toggleClass('focus')});

or

$("input,select,textarea").bind('focus blur',function() {$(this).toggleClass('focus')});
Chad Grant
Easier to read and understand too.
Stephen Denne
+1 for toggleClass
Winston Smith
perfect, thanks!
Mike
@Mike: Then you can accept the answer..
Vijay Dev
sorry, I'm a new for this excelent site, the answer is accepted now.
Mike
@Mike: That's fine.
Vijay Dev
+1  A: 

This should work

$("input, textarea, select").focus(function () {
   $(this).addClass('focus');
}).blur(function(){
   $(this).removeClass('focus');
});
Rafael
good example, will try to use.thanks.
Mike