Remove / add CSS class on input focus / blur

Morten Hagh picture Morten Hagh · Jun 23, 2012 · Viewed 39.2k times · Source

I have a form with some input fields and a little <div> to the right of each input with a little description. What I want is to enable a CSS class for each input's own <div> with it's own description.

I have made a working example here: http://jsfiddle.net/VL2FH/8/. This uses the <div> :hover state on the input's focus state.

What I want to ask is: Is there some sort of a "shortcut" so I don't have to make:

$('#submit_name').bind('blur', function(){
   $('#submit_name-desc').removeClass('input-desc-hover').addClass('input-desc');
});
$('#submit_name').bind('focus', function(){
  $('#submit_name-desc').removeClass('input-desc').addClass('input-desc-hover');
});
​

For each input field in the form.

Answer

Prasenjit Kumar Nag picture Prasenjit Kumar Nag · Jun 23, 2012

You can generalize the focus and blur callback like this

$('input').on('blur', function(){
   $(this).next('div').removeClass('input-desc-hover').addClass('input-desc');
}).on('focus', function(){
  $(this).next('div').removeClass('input-desc').addClass('input-desc-hover');
});

If your description divs are next to the input element, it will work fine.

And it's better to use .on() for event binding. ​

Demo: http://jsfiddle.net/joycse06/VL2FH/11/