23

Google Reader has a nice feature that when you switch to the web page from a different web page (giving the page focus) it will show you the updates there were accumulated while the page was unfocused.
Quick question #1: How do they do that?

I figure that they might be binding to the mouse move events + keyboard events since I don't know any out of the box event that gives you that ability.

Googling for that is a nightmare (focus, tab, web page, user).

Quick question #2: Is there some package out there that gives me that ability?

I'm putting the jQuery tag as a beacon for all the web developers ninjas out there, but I don't really care about the framework (as long as its Javascript)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Shay Erlichmen
  • 31,691
  • 7
  • 68
  • 87

5 Answers5

24

Try using jQuery's focus and blur functions:

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

$(window).blur(function() {
   console.log('bye bye');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click in and out of this frame to test the focus and blur functions.
Ethan
  • 4,295
  • 4
  • 25
  • 44
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
  • 2
    jquery focus doesn't act like hover(function(), function()) (which is a shame), I needed to bind to the blur event for "focusOut" – Shay Erlichmen Jan 10 '11 at 20:53
  • 1
    Aight lol. Ofc you're right. My mistake, I switched the two. It should act like you said though :) Would be a nice feature. Thanks for improving it and accepting it :). – PeeHaa Jan 10 '11 at 21:40
5

Use focusin (focus) and focusout (blur) on the document object:

$(document).bind('focus', function() {
   console.log('welcome (back)');
}).bind('blur', function() {
   console.log('bye bye');
});
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • 2
    I don't think OP wants to be notified every time any field on the page receives focus. Just when you switch to a page. – Ruan Mendes Jan 10 '11 at 20:39
5

I tested in FF and document.onfocus is called when I switch to that window.

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
5

The opposite of focus is blur.

document.addEventListener("focus", function(){
  console.log("Page in focus")
})

document.addEventListener("blur", function(){
  console.log("Page out of focus")
})
NVRM
  • 11,480
  • 1
  • 88
  • 87
2

There's a difference between the focus/blur events discussed by other answers, and the actual Visibility API. The best resource for this is the docs at MDN: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API

The Busy Wizard
  • 956
  • 1
  • 7
  • 11