Last active
December 17, 2015 04:19
-
-
Save digitarald/5549799 to your computer and use it in GitHub Desktop.
Detect language changes when switching to app. I personally recommend setting current language only on app launch. Reacting to changes later benefits only a small set of users, focus on the 99%!
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
// Example code, use with caution! | |
// Events and .hidden property requires no prefix since 18 | |
// Set current language on launch | |
document.documentElement.lang = navigator.language; | |
function visibilityChange() { | |
// user went off page, ignore | |
if (document.hidden) return; | |
// get current language and compare it to old one | |
var language = navigator.language; | |
var element = document.documentElement; | |
if (element.lang == language) return; // no change | |
element.lang = language; | |
// propagate change with an imaginary event (implement your own) | |
var evt = document.createEvent('Event'); | |
evt.initEvent('languageChange', true, false); | |
evt.language = language; | |
document.dispatchEvent(evt); | |
} | |
// Add event listener. | |
document.addEventListener('visibilitychange', visibilityChange, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code should probably not restrict the language to a substr, but the rest sounds like a feasible approach.