简体   繁体   中英

Using JQuery to bind “focus” and “blur” functions for “window”, doesn't work in IE

I need to use JQuery like the follwoing:

var focusFlag = 1;
jQuery(window).bind("focus", function(event)
{
focusFlag = 1;
});

jQuery(window).bind("blur", function(event)
{
focusFlag = 0;
});

Does anyone know why this doesn't work for IE?

Just to have the right answer here:

$(function() {
    $(window).focus(function() {
        console.log('Focus');
    });

    $(window).blur(function() {
        console.log('Blur');
    });
});

Note that in FF and IE the "Focus" event fires on ~document load, while in Chrome it only fires if the window had lost focus before and now it has regained it.

I'm only repeating what Shedal and roosteronacid have said, you need the DOM to be ready before you can bind events to it otherwise in some browsers computer will say no and it will die silently.

To do this you use the jQuery .ready() function explained by roosteronacid:

var focusFlag = 1;

jQuery(document).ready(function(){
    jQuery(window).bind("focus",function(event){
        focusFlag = 1;
    }).bind("blur", function(event){
        focusFlag = 0;
    });
});

What it does is the .ready() function will only fire and run the code inside it when the DOM has completely loaded from the server.

The only real changes I have made is that I hug my brackets for easy reading but it's a personal preference.

$(window)

does not work in all browsers.

Try

$('body') 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM