JQuery browser language definition

Scenario

I need to create a page (only on the client side) that determines which language the browser uses and displays the corresponding class element related to that language and hides the rest.

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

I use the value navigator.language and navigator.userLanguage (IE) to determine which language the browser is currently in use.

I currently have code that is executing, but I'm not sure how to make the best use of all the possible features, and then select them using an array.

It is also possible to connect more than one language to the country. Say, for example, English as an example has en-us, en-uk, etc. How do I tie this up?

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 a complete solution that worked for me and ultimately help future users, I used the same HTML layout on top and combined it with putvande jQuery solution .

Here is a working example .

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

  • Go to settings →
  • Scroll down and click "Show advanced settings ..." →
  • Click "Language and input settings ..." →
  • Then select the desired language, click on it and restart the browser.

Hope this helps.

+6
source share
1 answer

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

 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 will you also change li depending on the country (for example, in English and English)?

+13
source

Source: https://habr.com/ru/post/952042/


All Articles