Search code examples
jqueryclickwindowfocusblur

JQuery, first window click, next focus


How can i first call function click and next focus the window in jQuery? I tried:

$(window).click(function(){
    console.log(1);
});

$(document).focus(function(){
    console.log(2);
});

$(document).blur(function(){
    console.log(3);
});

but $(document).focus and .blur don't work

Code that I have, for example:

var isActive = false, wasClick = false;
$(window).click(function()
{
    if (!$(this).hasClass('button') && !$(this).hasClass('otherElement'))
    {
        isActive = false;
        wasClick = false;
        console.log('unactive varible');
    }
});

$(window).focus(function()
{
    if (wasClick) 
    {
        isActive = true;
        wasClick = false;
        console.log('focus');
    }
});

$(window).blur(function()
{
    if (isActive)
    {
        wasClick = true;
        isActive = false;
        console.log('blur');
    }
});

$('.button').click(function()
{
    isActive = true;
    console.log('button click');
});

I perform the following steps:

  1. Click button
  2. I click to other program in windows
  3. I back to my page by click to background

Output console:

button click
blur
focus
unactive varible

I want:

button click
blur
unactive varible

Solution

  • As far as I know, the focus event isn't as reliable (at least not in all browsers) on the window object. You can periodically check on the focus status of the page by using document.hasFocus(), but that's not entirely what you are looking for, I presume?