hubrid
hubrid

Reputation: 155

jQuery toggle focus / blur

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

Upvotes: 9

Views: 37375

Answers (4)

TheCrazyProfessor
TheCrazyProfessor

Reputation: 949

Blur only gets active when you leave an input, so you can use it to remove the focus again.

$('input').focus(function(){
    $(this).css('box-shadow', '0px 0px 1px #ccc');
});
                    
$('input').blur(function(){ 
    $(this).css('box-shadow', 'none');
});

Upvotes: 2

vsync
vsync

Reputation: 130065

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>

Upvotes: 27

mattsven
mattsven

Reputation: 23253

Try

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

Upvotes: 12

bluefoot
bluefoot

Reputation: 10570

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');
});

Upvotes: 7

Related Questions