jQuery handing both focus and click on an element

醉酒当歌 提交于 2019-11-28 08:34:04
Juan Mendes

Here's something that I think works based on the fact that the mousedown happens before the focus. See demo.

var lastClick = null;
$('input').mousedown(function(e) {
  lastClick = e.target;
}).focus(function(e){
    if (e.target == lastClick) {
      console.log('click');
    } else {
      console.log('tab');    
    }
    lastClick = null;

});

To fix the bug discovered by Josiah, I changed my code to the below. See demo.

var lastFocusedElement = null;
var isClick = false;
$('input').mousedown(function(e) {     
     isClick= true;
}).focus(function(e){

    // To prevent focus firing when element already had focus
    if (lastFocusedElement != e.target) {
        if (isClick) {
          console.log('click ----');
        } else {
          console.log('tab -----');    
        }
        lastFocusedElement = e.target;
        isClick = false;
    }
});

$(document.body).focus(function(){
  lastFocusedElement = document.body;
});

The one problem is that you don't get 'click' or tab when you switch away from the window and switch back. You get a focus event on the input that had focus, but you can't determine if it's a tab or a click, because it's neither.

I think this is the closest you'll get, I would try this on your page and see if the behavior is good enough.

You could use the .on() method in jQuery. Here is another way to bind both events on the same element.

var hasClicked = false;
$('.myinputfield').on('mousedown : click',function(e){
     if (e.type == 'mousedown') {
        // execute code
        hasClicked = true;
     }
     if(e.type == 'focus' && !hasClicked) {
        //execute code
        console.log(e.type)
     }
     hasClicked = false;
});

Just bind the focus and then check the event to see if e.which == 9 // tab.

My original idea did not work (thanks @Juan). Using the combination of events should get you where you want to be. If the user clicks into the text box the last key press will not be a tab. All inputs are watching and storing the last key code to pass to the focus event. here is the fiddle

var lastKeyCode = 0;
$('input').focus(function(e) {
    if(lastKeyCode == 9)
         // tabbed into field
    else
         // clicked into field
}).keydown(function(e){
    if(e.which == 9) // added timeout to clear lastkeypress
        setTimeout(function(){lastKeyPress = 0}, 50);
    lastKeyPress = e.which; // store last key code
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!