Window focus() The focus() method sets focus to a window.
The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it). The focus() method triggers the focus event, or attaches a function to run when a focus event occurs. Tip: This method is often used together with the blur() method.
Note : In jQuery blur( handler ) method is used to bind an event handler to the "blur" JavaScript event, or trigger that event on an element. It has the following parameter : handler : A function to execute each time the event is triggered.
jQuery blur() Method The blur event occurs when an element loses focus. The blur() method triggers the blur event, or attaches a function to run when a blur event occurs. Tip: This method is often used together with the focus() method.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With