Detect focus initiated by tab key?

北慕城南 提交于 2019-11-29 02:49:31

I know you have accepted an answer but you could test the button pressed using the following:

$('#detect').on('focus', function(e){
    $(window).keyup(function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 9) {
           alert('I was tabbed!');
        }
    });
});

http://jsfiddle.net/LPGLm/1/

Edit: change the listener around:

$(window).keyup(function (e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 9 && $('#detect:focus').length) {
        alert('I was tabbed!');
    }
});

http://jsfiddle.net/LPGLm/7/

A more responsive solution would be to use two listeners:

var mousedown = false;
$('#detect').on('mousedown', function () {
    mousedown = true;
});

$('#detect').on('focusin', function () {
    if(!mousedown) {
        // logic
    }
    mousedown = false;
});

Fiddle showing the difference in speed:

http://jsfiddle.net/u2y45/1/

As you've noticed, the event object itself does not distinguish the means of access. What you can do is to bind a mousedown listener, which will fire before focus, and set some timestamp flag that you compare to some threshold value in your focus handler.

You can check focus event on specific input by this code

$(window).on('keyup', function(event){
    if(event.keyCode == '9'){

      getFocused(event);
    }

})
var focused = 0;
function getFocused(e){
var ida =  $(':focus').eq(0).prop('id');
    if(ida=='detect' && focused==0){
        focused = 1;
        console.log(e);
    }
}

(fiddle)

<input type="text" id="foo" />
<input type="text" id="detect" />
<script>
 $("#foo").on('keyup', function(){    
   document.getElementById("detect").value = "007";  
    alert("your tab active successfully");  
   });  
 </script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!