jQuery toggle focus / blur

34,745

Solution 1

Try

$('.answerSpace').bind('blur', function(){ $('.normProf').removeClass("normProf").addClass('opacProf'); });
$('.answerSpace').bind('focus', function(){ $('.opacProf').removeClass("opacProf").addClass('normProf'); });

Solution 2

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>

Solution 3

Well, if I get you right, you can use onblur and onfocus events, with the toggleClass function:

$('#yourelement').bind('blur', function(){
    $(this).toggleClass('your-class');
});

$('#yourelement').bind('focus', function(){
    $(this).toggleClass('your-class');
});
Share:
34,745

Related videos on Youtube

hubrid
Author by

hubrid

Updated on June 14, 2020

Comments

  • hubrid
    hubrid almost 4 years

    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...

  • hubrid
    hubrid about 13 years
    Hmmm, if I use this, the css changes on the first focus. Then it doesn't change back on the blur. Nor the second blur. But actually on the third blur it then reverts to the previous css. The code I'm using is above.
  • John Magnolia
    John Magnolia about 11 years
    You could combine the bind('blur focus')
  • Pete
    Pete over 9 years
    This is the most elegant solution here.

Related