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');
});
Related videos on Youtube
Author by
hubrid
Updated on June 14, 2020Comments
-
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 about 13 yearsHmmm, 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 about 11 yearsYou could combine the
bind('blur focus')
-
Pete over 9 yearsThis is the most elegant solution here.