Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove / add CSS class on input focus / blur

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.

like image 273
Morten Hagh Avatar asked Jun 23 '12 13:06

Morten Hagh


Video Answer


1 Answers

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/

like image 57
Prasenjit Kumar Nag Avatar answered Oct 15 '22 20:10

Prasenjit Kumar Nag