1

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

1 Answers1

1

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?

  • Ohh thanks, i don't think about this, but it work when i add it to $(window).focus : $(window).focus(function() { if (!document.hasFocus()) return false; if (wasClick) { isActive = true; wasClick = false; console.log('focus'); } }); Thanks so much! – Łukasz Pietuchowski Jan 24 '17 at 00:04
  • Glad to be of help! – Geert van Dijk Jan 24 '17 at 00:09
  • Ohh and this don't work. And this have some bugs.. sometimes bypasses document.hasFocus(), and when i example switch cards then blur and focus function run several times.. – Łukasz Pietuchowski Jan 24 '17 at 00:30
  • Haven't tested this myself, but a quick search returned this, which might be useful: http://stackoverflow.com/questions/1760250/how-to-tell-if-browser-tab-is-active Perhaps the second code part of the accepted anwer might work for you? – Geert van Dijk Jan 24 '17 at 00:35
  • I read this, but i create something else. I have $(window).click and i want check result this function before $(window).focus - only if window was click (look code in the first post) – Łukasz Pietuchowski Jan 24 '17 at 00:40
  • okey, I checked everything and document.hasFocus() work, but have sometimes bugs. Thanks for that – Łukasz Pietuchowski Jan 24 '17 at 00:53