Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event when a web page gets focused

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)

like image 221
Shay Erlichmen Avatar asked Jan 10 '11 20:01

Shay Erlichmen


People also ask

What is a focus event?

The focus event fires when an element has received focus. The main difference between this event and focusin is that focusin bubbles while focus does not. The opposite of focus is blur . This event is not cancelable and does not bubble.

What HTML event happens when an element loses focus?

The onfocusout event occurs when an element is about to lose focus.

Which event fires when the page comes into the browser?

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images.


2 Answers

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.
like image 52
PeeHaa Avatar answered Oct 05 '22 03:10

PeeHaa


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

like image 32
Juan Mendes Avatar answered Oct 05 '22 05:10

Juan Mendes