views:

548

answers:

4

I have no idea how to handle localization with JQuery. I want to set an innerHTML with German text, but if the browser is configured to use English, then I want to set English text.

In PHP I use gettext for such stuff, but how to do it in JavaScript/jQuery?

+2  A: 

There is no easy solution for that. What I would probably do is create several scripts with language texts for every language and include proper one in PHP. So if someone is using english version of your site you would include only english file, if someone is using german version you would include german language file etc.

Example:

// your script logic
myscript.js

// language texts
myscript.en.js
myscript.de.js
myscript.it.js
...

You can define all language files like that:

LANG = {
    txt1: 'English text1',
    txt2: 'English text2'
    ...
};

Make sure you are including only one of those in your HTML and make sure to include language file first i.e.

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

Then you can use those localized texts in your main script for example:

$(document).ready(function () {
    alert(LANG.txt1);
});

What's best about it is that your logic (myscript.js in this example) doesn't have to worry about localization and you won't have to change it if you want to add a new language file.

RaYell
+2  A: 

You actually don't need JQuery at all.

The navigator object in javascript (http://www.comptechdoc.org/independent/web/cgi/javamanual/javanavigator.html) contains a userLanguage(IE) and language(Netscape/Firefox) property that is set by the browser's current locale.

To solve your example you could use something like;

   
  var textToSet = null;
  var userLang = null;

  /*
  -if userLanguage exists they're in IE, else firefox
  -get the first two letters in lowercase to guarantee 
   an easily evaluated base language
  */
  if(navigator.userLanguage) baseLang = substring(navigator.userLanguage,0,2).toLowerCase();
  else baseLang = substring(navigator.language,0,2).toLowerCase();

  //check languages
  switch(baseLang)
  {
    case "de":
      //German
      textToSet = "german text";
      break;
    default:
      textToSet = "english text";
  }
  document.getElementById('elementToSetTextInto').innerHTML = textToSet;


Keep in mind, you might want different text based off of base language and locale.. in that case look for "en-us", "de-de". Sites for culture codes are easily googled (1 link on first post only ;))

Hope that works out for ya.

A: 

http://keith-wood.name/localisation.html http://www.novogeek.com/post/2009/11/30/Client-side-localization-in-ASPNET-using-jQuery.aspx

mirza
A: 

Give this a try. The TranslateThis Button is a lightweight Javascript translation widget. It translates any page quickly using AJAX and the Google Language API.

Here...

ctrlShiftBryan