jQuery focus/blur on form, not individual inputs

后端 未结 4 632
臣服心动
臣服心动 2020-12-18 05:46

How could this be achieved via jQuery?

When the user clicks on any input in the form, it is focussed. When a user clicks out of the form from any input it is blurred

相关标签:
4条回答
  • 2020-12-18 06:13

    would $('form').focusin()/focusout() not work?

    http://api.jquery.com/focusout/

    0 讨论(0)
  • 2020-12-18 06:19

    You could do something like this:

    var check;
    
    $('form input').focus(function()
       {
        clearInterval(check); // remove setinterval if any
        // do something because the form is being used
       });
    
    $('form input').blur(function()
    {
        check = setInterval(function()
        {
            // do something because the form is not being used
        },500); // half-second delay
    });
    

    It's not the sexiest solution, but checks for if no focus in your form occurs after .5 seconds. Hope this helps.

    0 讨论(0)
  • 2020-12-18 06:33

    Here's the same basic idea as Alexey's but for jQuery 1.7+ and, at least to my mind, a little more readable because it keeps everything in scope within the same handler:

        $("#myform").on("focusout focusin", "input", function(e){
            if ( e.type == "focusout" ) {
                $("#myform").attr("form-blur-timeout", window.setTimeout(function(){
                    console.log("you've left the form!");//do stuff here
                }, 100));
            } else {
                window.clearTimeout($("#myform").attr("form-blur-timeout"));
            }
        });
    

    Enjoy :)

    0 讨论(0)
  • 2020-12-18 06:38

    The sequence of events when you're tabbing between inputs:

      Click on input1:  input1 focus
    
      Clickb on input2: input1 blur
                        input2 focus
    
      Click outside:    input2 blur
    

    When an input loses focus you need to check if some other element within the form gains focus. Or you can simply check if the active element is still within the form:

    $('form').on('focusout', function(event) {
        setTimeout(function() {
            if (!event.delegateTarget.contains(document.activeElement)) {
                console.log('Form blur');
            }
        }, 0);
    });
    

    JSFiddle

    Note that form doesn't blur on submit, so you may need to add a submit handler if you want to do the same thing on blur and submit.

    Also note the use of setTimeout, it's required because blur and focusout events are emitted when an element is about to lose focus, but haven't lost it yet.

    0 讨论(0)
提交回复
热议问题