jQuery toggle focus / blur

hubrid picture hubrid · Apr 9, 2011 · Viewed 32.3k times · Source

How can I toggle an element's CSS on focus/blur with jQuery?

$('.answerSpace').bind('blur', function(){
$('.normProf').toggleClass('opacProf');
});

$('.answerSpace').bind('focus', function(){
    $('.opacProf').toggleClass('normProf');
});

So now I have this. But it doesn't quite work...

Answer

vsync picture vsync · Aug 12, 2014

Check this out, it's exactly how y'all should do jQuery focus toggle..

Basic use case:

$('input').on('focus blur', toggleFocus);

function toggleFocus(e){
    console.log(e.type)

    if( e.type == 'focusin' ){ 
      // do something on focus
    }
    else{
      // do something else on blur
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>