Wulf
Wulf

Reputation: 3898

jquery focusin doesn't work when calling .focus() and return false;

I have a problem with the focusin/focusout events of jQuery (1.7.2).

I have 2 inputs in a div. When one of them gains focus, I want to add a class to the div. I only want to remove this class, if none of the inputs has focus anymore.


$(function() {
  $('#container').on('focusin',function(){
    $(this).addClass('test');
  }).on('focusout',function(){
    if ($(this).find('input:focus').length) return;
    $(this).removeClass('test');
  });

  $('#container input').on('keydown',function(e) {
    var keycode = e.keyCode || e.which;
    //When Tab or Return, switch input
    if (keycode == 9 || keycode == 13) {
      $($(this).attr('data-target')).focus();
      return false;
    }
  });
});

<div id="container">
    <input type="text" id="a" data-target="#b">
    <input type="text" id="b" data-target="#a">
</div>

http://jsfiddle.net/pqUFX/

Works fine, when I click into the inputs with my mouse to switch the focus. But when setting the focus to the other input inside the keydown() event of the input by calling $('#b').focus(); the class gets removed, even when checking for existing focuses inside the div.

Is it perhaps because of my return false;, so the tab doesn't switch twice? Do you have any alternative solution for this?

Upvotes: 0

Views: 1968

Answers (1)

Agustin Lopez
Agustin Lopez

Reputation: 1365

Not sure why it not works really (it should) but why don't you use something like this:

$(function() {
    $('#container input').on('keydown',function(e) {
        var keycode = e.keyCode || e.which;
        //When Tab or Return, switch input
        if (keycode == 9 || keycode == 13) {             
            $($(this).attr('data-target')).focus();
            $(this).parent().addClass("test");
            return false;
        }
    }).focusin(function() {
        $(this).parent().addClass("test");                  
    }).focusout(function() {
        $(this).parent().removeClass("test");                  
    });
});​

Upvotes: 1

Related Questions