Skip to content

Instantly share code, notes, and snippets.

@digitarald
Last active December 17, 2015 04:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digitarald/5549799 to your computer and use it in GitHub Desktop.
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%!
// 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);
@Pike
Copy link

Pike commented May 16, 2013

This code should probably not restrict the language to a substr, but the rest sounds like a feasible approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment