Last active
February 28, 2016 08:52
-
-
Save molovo/474cf84c8fa3fc2bc445 to your computer and use it in GitHub Desktop.
Quick bit of JS to change page title when the user navigates away from the tab
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
( function () { | |
// This function does the dirty work of finding the event type and setting the appropriate title | |
var updatePageTitle = function ( evt ) { | |
var v = "This text should match your <title> element", // The title when tab is visible | |
h = "I Miss You! ❤", // The title when tab is hidden | |
evtMap = { | |
focus: v, | |
focusin: v, | |
pageshow: v, | |
blur: h, | |
focusout: h, | |
pagehide: h | |
}; // Map each title to the different events | |
evt = evt || window.event; | |
// If the event type exists in the map, set the right title | |
if ( evt.type in evtMap ) { | |
document.title = evtMap[ evt.type ]; | |
} else { | |
// Last ditch attempt | |
if ( document.hidden ) { | |
document.title = h; | |
} else { | |
document.title = v; | |
} | |
} | |
}; | |
// This sets the appropriate listeners so that everything works cross browser | |
var hidden = "hidden"; | |
// Standards: | |
if ( hidden in document ) | |
document.addEventListener( "visibilitychange", updatePageTitle ); | |
else if ( ( hidden = "mozHidden" ) in document ) | |
document.addEventListener( "mozvisibilitychange", updatePageTitle ); | |
else if ( ( hidden = "webkitHidden" ) in document ) | |
document.addEventListener( "webkitvisibilitychange", updatePageTitle ); | |
else if ( ( hidden = "msHidden" ) in document ) | |
document.addEventListener( "msvisibilitychange", updatePageTitle ); | |
// IE 9 and lower: | |
else if ( "onfocusin" in document ) | |
document.onfocusin = document.onfocusout = updatePageTitle; | |
// All others: | |
else | |
window.onpageshow = window.onpagehide = window.onfocus = window.onblur = updatePageTitle; | |
} )(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment