Computer projects

Changing the Page Title When a Browser Tab Loses Focus, as Ele.me Does

Here's how to change a page's title with JavaScript when its browser tab loses focus. The API itself is very simple and consists of three parts. document.hidden: a boolean indicating whether the page is hidden. A page is hidden when it is in a background tab or the browser is minimized. document.visibilityState: a value representing one of four possible states. hidden: the page is in a background tab or the browser is minimized. visible: the page is in the foreground tab. prerender: the page is being prerendered off-screen, and document.hidden is true. unloaded: the page is being unloaded from memory. The visibilitychange event fires when the document changes from visible to hidden or from hidden to visible. We can therefore listen for visibilitychange, read document.hidden when it fires, and update the title accordingly.

Remember: this only works in browsers that support HTML5.   Code:


var OriginTitile = document.title; var titleTime; document.addEventListener('visibilitychange', function() { if (document.hidden) { document.title = '(つェ⊂)I’m hiding now~ ' + OriginTitile; clearTimeout(titleTime); } else { document.title = '(*´∇`*) You found me~ ' + OriginTitile; titleTime = setTimeout(function() { document.title = OriginTitile; }, 2000); } });


Finally, enable the JavaScript in WordPress using the Custom Javascript plugin.

Published 04/14/2018 · Krunk Zhou

Join the conversation