Mike
Mike

Reputation: 1863

Please help to optimize simple JQuery functions

I have a such functions 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?

Upvotes: 1

Views: 228

Answers (2)

Chad Grant
Chad Grant

Reputation: 45382

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

or

$("input,select,textarea").bind('focus blur',function() {$(this).toggleClass('focus')});

Upvotes: 9

Rafael
Rafael

Reputation: 18522

This should work

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

Upvotes: 2

Related Questions