Search code examples
jqueryfocusoutfocusin

How to prevent focusout when focusin fires on the same element?


I'm attaching an .active class to a div that is wrapped around an input and label.

My problem is when an element is clicked inside the wrapped DIV, the focusout will fire, and this is causing a slight flicker of the styling.

$('body')
    .on('focusin', '.formlabel', function() {

        $(this).addClass('active');

    })
    .on('focusout', '.formlabel', function() {

        $('.formlabel').removeClass('active');

    });

Here's an example: http://jsbin.com/mamacogimo/1/edit?html,js,output - click the label and an item from the dropdown. You will notice the blue background flickers.

Is there anyway to prevent the flickering?


Solution

  • You can use a timeout, like so:

    var timeout;
    $('body').on('focusin', '.formlabel', function() {
      $(this).addClass('active');
    
      clearTimeout(timeout);
    
    }).on('focusout', '.formlabel', function(e) {
      timeout = setTimeout(function() {
        $('.formlabel').removeClass('active');
      }, 250);
    });
    

    http://jsbin.com/dafubiweto/2/edit