|
| 1 | +--- |
| 2 | +--- |
| 3 | + |
| 4 | +$(document).ready(function() { |
| 5 | + var currentLocale = $('html').attr('lang'); |
| 6 | + |
| 7 | + // All available translations |
| 8 | + var translations = $('a.locale-chooser'); |
| 9 | + |
| 10 | + // Get the preferred locale |
| 11 | + var locale = getLocaleFromQuery() |
| 12 | + || getLocaleFromCookie() |
| 13 | + || getLocaleFromBrowser(translations); |
| 14 | + |
| 15 | + // If preferred locale is not the same as the current locale, then set it. |
| 16 | + if (locale && locale != currentLocale) { |
| 17 | + translations.filter("[lang=" + locale + "]").click(); |
| 18 | + } |
| 19 | + |
| 20 | + // Set locale when clicking on locale link |
| 21 | + translations.on('click', function(event) { |
| 22 | + setLocale($(event.target).attr('lang')); |
| 23 | + }); |
| 24 | +}); |
| 25 | + |
| 26 | +// Save the preferred locale in a cookie, which will be set on any subdomain. |
| 27 | +function setLocale(locale) { |
| 28 | + document.cookie = 'locale=' + locale; |
| 29 | +} |
| 30 | + |
| 31 | +// Get locale from the `l` parameter of the query string |
| 32 | +function getLocaleFromQuery() { |
| 33 | + return window.location.search.replace(/.*[?&]l=([^&$]+).*/, '$1'); |
| 34 | +} |
| 35 | + |
| 36 | +function getLocaleFromCookie() { |
| 37 | + return document.cookie.replace(/(?:(?:^|.*;\s*)locale\s*\=\s*([^;]*).*$)|^.*$/, '$1'); |
| 38 | +} |
| 39 | + |
| 40 | +// Use locale that matches browser's preferred locales |
| 41 | +function getLocaleFromBrowser(translations) { |
| 42 | + var browserLocales = [].concat(navigator.languages || navigator.userLanguage || navigator.language); |
| 43 | + for(var i = 0; i < browserLocales.length; i++) { |
| 44 | + if (translations.filter('[lang=' + browserLocales[i] + ']').length) { |
| 45 | + return browserLocales[i]; |
| 46 | + } |
| 47 | + } |
| 48 | +} |
0 commit comments