Search code examples
javascriptjquerywindowonblur

On submit, after X seconds, if window blur


I am trying to identify if the window loses focus after 3 seconds of submit.

Currently I have this:

$("input").on("submit",function(){
$(window).blur(function(){
  console.log(a);
})
});

But this, no matter when you press submit, if you click outside the window or minimize the window the console.log triggers a.

This is what I am trying to achieve:

  1. User submits form
  2. In a period of 3 seconds, if the window loses focus do console.log(a);
  3. After 3 seconds, if the window loses focus do nothing.
  4. If the user submits again on the same session, repeat from step 1.

Solution

  • Try this:

    $("#form").on("submit",function(){
        var blurFunc = function() {
            console.log(a);
        }
    
        $(window).blur(blurFunc);
        setTimeout(function() { $(window).unbind('blur', blurFunc); }, 3000);
    });
    

    The setTimeout call will unbind from the blur event after 3 seconds, causing the event to not fire.

    For more info on setTimeout see here: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

    Alternatively, you could do something like this:

    $("#form").on("submit",function(){
        var submitted = true;
    
        var blurFunc = function() {
            if(submitted) {
                console.log(a);
            } 
        }
    
        $(window).blur(blurFunc);
        setTimeout(function() { submitted = false; }, 3000);
    });