jQuery handing both focus and click on an element

前端 未结 3 1826
暗喜
暗喜 2020-12-09 11:28

I\'m trying to determine workflow to fine-tune a data entry web application. Picture several address forms on a single web page:

  1. Name___________
     S         


        
3条回答
  •  天命终不由人
    2020-12-09 12:15

    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.

提交回复
热议问题