using the script descripted below, i was wondering if there was a way to put a link on the page to allow users to change the displayed language after the page is loaded. Initialy, it displays the default language of the users but i want to allow them to change it if they want dynamicaly.
Thanks!
Thomas
The usual approach is to keep the languages separate (one HTML file per language for example) and send the content back in the language they want. You could try to parse the Accept-Language header and send back the closest match; you'd probably want to include a language selection widget of some sort as well.
If you really want to do this on the client with JavaScript then you should:
Set the lang attribute on each piece of content (or wrapper `s). Grab the language from navigator.language or navigator.userLanguage (check them both, the latter is for IE, the first is, AFAIK, everyone else) and have a suitable default in hand just in case. Then show everything whose lang matches the language and hide everything whose lang doesn't match. For example, if you have this HTML:
<div lang="en" class="wrapper">
<h1>English</h1>
<p>Here is some English content.</p> </div> <div lang="fr" class="wrapper" style="display: none;">
<h1>Française</h1>
<p>Voici le contenu en français.</p> </div> <div lang="pt" class="wrapper" style="display: none;">
<h1>Português</h1>
<p>Aqui você encontra o conteúdo Português.</p> </div> And then some JavaScript (I'll use jQuery as that's my weapon choice)
> $(document).ready(function() {
> var known = { en: true, fr: true, pt: true };
> var lang = (navigator.language || navigator.userLanguage || 'en').substr(0, 2);
> if(!known[lang])
> lang = 'en';
> // Find all <div>s with a class of "wrapper" and lang attribute equal to `lang`
> // and make them visibile.
> $('div.wrapper[lang=' + lang + ']').show();
> // Find all <div>s with a class of "wrapper" and lang attribute not equal
> // to `lang` and make them invisibile.
> $('div.wrapper[lang!=' + lang + ']').hide(); });
Here's a live example: http://jsfiddle.net/ambiguous/hDM3T/2/
If you keep the show/hide logic in a separate function that takes a language argument then it would be pretty easy to provide a language selection widget of some sort too.
You could also use a class for the language if that's easier to work with using your JavaScript tools but leaving the lang attribute around would be a good idea.