Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 904
hubrid Avatar asked Apr 09 '11 21:04

hubrid


People also ask

How to use focus and blur in jQuery?

jQuery blur() Method The blur event occurs when an element loses focus. The blur() method triggers the blur event, or attaches a function to run when a blur event occurs. Tip: This method is often used together with the focus() method.

How to focus out using jQuery?

jQuery focusout() MethodThe focusout() method attaches a function to run when a focusout event occurs on the element, or any elements inside it. Unlike the blur() method, the focusout() method also triggers if any child elements lose focus. Tip: This method is often used together with the focusin() method.

How to focus button in jQuery?

The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button. Here selector is the selected element. Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.

What is the difference between Blur and Focusout?

The main difference between this event and blur is that focusout bubbles while blur does not. The opposite of focusout is focusin .


1 Answers

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>
like image 129
vsync Avatar answered Nov 09 '22 05:11

vsync