简体   繁体   中英

jQuery browser language detection

Scenario

I'm in need to create a page (client-side only) that detects what language the browser is using and displays the appropriate class element relating to that language, and hides the others.

English would be the default language, so if none of the cells in the array are matched, this would be displayed.

I'm using the navigator.language and navigator.userLanguage (IE) value to detect which language the browser is currently using.

I currently have some code that's in progress, but i'm not sure of the best way to incorporate all the potential possibilities and then select them using an array.

There's also the possibility of more than one language being tied with a country. Say for instance English as an example has en-us, en-uk etc.. How would I tie this in?

Code

HTML

<ul class="text">
    <li class="en active">English: Some text in english</li>
    <li class="fr">French: Some text in french</li>
    <li class="de">German: Some text in german</li>
    <li class="it">Italian: Some text in italian</li>
    <li class="ja">Japanese: Some text in japanese</li>
    <li class="es">Spanish: Some text in spanish</li>
</ul>

JS (WIP)

var userLang = navigator.language || navigator.userLanguage,
    countries = ['fr', 'de', 'it', 'ja', 'es'],
    languagues = ['fr', 'de', 'it', 'ja', 'es'];

if (userLang === "fr") {
    $('li').removeClass('active');
    $('.fr').addClass('active');
}

Example

Fiddle

Thank you for your time.


UPDATE

To provide the full solution that worked for me and to ultimately help future users, I used the same layout of HTML from above and combined it with putvande's jQuery solution .

Here is a working example .

NOTE: This effect triggers the changes depending on the language selected for the browser. As an example on how to do this in Google Chrome:

  • Go to the settings ->
  • Scroll down to and click "Show advanced settings..." ->
  • Click "Language and input settings..." ->
  • Then select you're desired language, click done and restart your browser.

I hope this helps.

You can split the navigator.language into two and only use the first parameter (the language) and use that to select the li that has that class:

var userLang = navigator.language || navigator.userLanguage;

// Check if the li for the browsers language is available
// and set active if it is available
if($('.' + userLang.split('-')[0]).length) {
    $('li').removeClass('active');
    $('.' + userLang.split('-')[0]).addClass('active');
}

Or are you also going to be changing the li according to the country (for example US and UK english)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM