最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - onfocusoutonfocusin not working - Stack Overflow

programmeradmin4浏览0评论

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>

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>

Share Improve this question asked Apr 8, 2016 at 12:09 BlackBlack 20.3k45 gold badges185 silver badges295 bronze badges 3
  • Area you talking about focus and blur events? – Ruby Racer Commented Apr 8, 2016 at 12:13
  • Look here: w3schools./jsref/event_onfocusin.asp and here w3schools./jsref/event_onfocusout.asp – Black Commented Apr 8, 2016 at 12:13
  • @RubyRacer developer.mozilla/en-US/docs/Web/Events/focusin – epascarello Commented Apr 8, 2016 at 12:17
Add a ment  | 

4 Answers 4

Reset to default 10

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

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

Add tabindex="1" attribute to your element that you want to receive/lose focus

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...

发布评论

评论列表(0)

  1. 暂无评论