1. Home
  2. Computing & Technology
  3. JavaScript

Automatic Language Selection

Join the Discussion

Questions? Comments?

Do you want to provide copies of your web pages translated into different languages? Javascript can't help you with producing the translations but it can help you in getting the right version of your page to display based on the language that your visitor uses.

The first step is to create the translated versions of all of your pages where you want to offer multiple versions. The script assumes that the translated versions will be distinguished from your default language version by the addition of a suffix to the actual filename. For example if your default language page is mypage.htm then the French translation of that page will be mypage-fr.htm. You need to use the standard two character language abbreviations to define your languages. The default language (usually English) will be the version without the language suffix and it will be the version that is displayed if you don't have a translated version in the required language available. We will add a script to the default language pages to automatically redirect to the appropriate translated version so all of the links should go to the default version of each page.

The next step in setting up our automatic language redirect is to copy the following script and save it as langdir.js.

You next need to update the langcodes array to contain the two character language codes for each of the languages that you have translated your pages into (the list currently contains French and Spanish but you can include whatever and as many languages as you have translated copies of your pages).

Finally we link the script into the head of each of our pages where translated versions are available by adding the following code:

<script type="text/javascript" src="langdir.js">
</script>

Now whenever anyone visits one of your default pages with the language in their browser set to one of those where you have a translation available their browser will automatically reload the appropriate translated version over the original.

You can easily add further language translations at a later date simply by creating all of the pages in the new language and then ading the language code to the langcode array in the script.

Explore JavaScript
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.