How to detect blur of browser tab and re focus of browser tab with jquery

April 19, 2011

Its been a while since I last posted anything on my blog, and its mainly not through the want of trying, but more that I haven't had the time to keep posting the things I find in my travels. However to try and keep up I have another interesting and potentially time saving / useful addition to make today.

How to detect when a user moves the focus of his/her browser to a different tab than yours. And also subsequently how to tell when your tab regains the focus of the user when they reselect it. This is useful why? Ever wondered how facebook and twitter update the title of the tab to inform you of how many messages or tweets you've missed out on while not focused on the tab. Then i'm just about to nail it.

It's really quite simple, but the usage of it can become complex and very useful, particuarly to the efficiency of your app. For instance if a page requires being updated by an intervalled ajax call say every 5 seconds when a user is focused on the tab. Perhaps when it loses focus you could increase the interval time, to say 30 seconds. As while they are not looking at the tab, they probably don't need to be updated so often. Then when they refocus you can just set it back to normal. This will improve the efficiency of your app.

Here's how it can be done with a tiny little bit of jQuery magic.

'); }); $(window).blur(function(){ document.write('blurred
'); }); });

Any questions i'll be happy to answer them, perhaps i'll even show you how you can turn this example into a more useful one later.

About me

Hello! I'm David Heward, how are you going? I'm a Senior Devops/Build Engineer, specialising in AWS & Cloud Automation. Based in London. Strong 10+ year background in Software development. Have a read of my blog. Have a look at some of my working projects. Contact me at @davehewy or on Linkedin.