Reputation: 20232
I just learned about onfocusout
, onfocusin
but these functions do not seem to work. I tried it both with firefox and chrome. There are no console messages at all, even when i have focus and loose it. What am i doing wrong?
window.addEventListener
(
"onfocusout",
function()
{
console.log("page lost focus");
}
);
window.addEventListener
(
"onfocusin",
function()
{
console.log("page has focus");
}
);
<h1>Test</h1>
Upvotes: 3
Views: 11268
Reputation: 927
Add tabindex="1"
attribute to your element that you want to receive/lose focus
Upvotes: 1
Reputation: 1725
Just use the below code snippet, it's easier to read but does the same as event handlers :-)
$(function(){
$('.yourfocuselement').focus(function(){
//The code for element focus goes here
})
$('.yourfocuselement').blur(function(){
//The code for element lose focus goes here
})
})
Also I may not know your full requirements from this code, but I don't see why you would need to add a listener for the page focus...
Upvotes: -1
Reputation: 207501
With addEventListener you do not use "on" with the event name
function example(evt) {
console.log(evt.type, event.target.id);
}
window.addEventListener("focusin", example);
window.addEventListener("focusout", example);
<input type="text" id="foo" />
<input type="text" id="bar" />
If you are wondering about the page state, than you need to look at different events: pageshow
and pagehide
Upvotes: 10
Reputation: 330
I've done some research regarding this. And you only gain "focus" when you actually select a text field. source: w3schools
So what you're looking for is for the console to log something when you minimize the screen? or select another window? If so i found a post regarding this here
Upvotes: 4