Click here to Skip to main content
15,886,110 members
Articles / Web Development / CSS3
Tip/Trick

How to Create a Multilingual Application using JavaScript

Rate me:
Please Sign up or sign in to vote.
4.83/5 (11 votes)
13 Jan 2017CPOL1 min read 46.9K   1.1K   7   4
A good demo of how you can easily create a multilingual application using JavaScript

Introduction

In this tutorial, you will learn an easy way to create a multilingual application based on resources language file.

Background

This tip may be useful for intermediate developers who have some basics in programming with JavaScript.

Using the Code

The main steps of this program are:

  1. Take desired language (en : 'English', fr : 'France') used to identify the resource file,
  2. Take attribute name used to identify the corresponding value from resources language file.
  3. Use the above information to replace specific HTML elements value to corresponding language.

a) Example of Used Resource File

English File (en.json)

JavaScript
{
    "contact":"Contact form",
    "email": "Email",
    "password": "Password",
    "subject": "Subject",
    "message": "Message"
}

French File (fr.json)

JavaScript
{
    "contact":"Formulaire de contact",
    "email": "Email",
    "password": "Mot de passe",
    "subject": "Sujet",
    "message": "Message"
}

b) Source Code

** Translate.js File

init: Initialize the attribute name and the desired language
process: This method goes through the below steps:
  1. Deserialize the content of language file into json object named 'LngObject'
  2. Find HTML elements having the same attribute name with 'attribute value'
  3. For each element, getting key name to retrieve value in corresponding language from 'LngObject'
  4. Replace the value of current HTML element with retrieved data
JavaScript
 function Translate() { 
    //initialization
    this.init =  function(attribute, lng){
        this.attribute = attribute;
        this.lng = lng;    
    }
    //translate 
    this.process = function(){
                _self = this;
                var xrhFile = new XMLHttpRequest();
                //load content data 
                xrhFile.open("GET", "./resources/"+this.lng+".json", false);
                xrhFile.onreadystatechange = function ()
                {
                    if(xrhFile.readyState === 4)
                    {
                        if(xrhFile.status === 200 || xrhFile.status == 0)
                        {
                            var LngObject = JSON.parse(xrhFile.responseText);
                            console.log(LngObject["name1"]);
                            var allDom = document.getElementsByTagName("*");
                            for(var i =0; i < allDom.length; i++){
                                var elem = allDom[i];
                                var key = elem.getAttribute(_self.attribute);
                                 
                                if(key != null) {
                                     console.log(key);
                                     elem.innerHTML = LngObject[key]  ;
                                }
                            }
                     
                        }
                    }
                }
                xrhFile.send();
    }    
}

** HTML File

When the main page has been loaded, the load function will be invoked to transform concerned elements value (which contain "data-tag" attribute) to corresponding language based on both arguments:

  • currentLng variable: Desired language
  • attributeName variable: The value given from this attribute of a specific HTML element is used to extract the corresponding value in the desired language.
HTML
<!DOCTYPE html>
<html>
 
<script src="translate.js"></script>
<script>
function load(){
    var translate = new Translate();
    var currentLng = 'en';//'fr'
    var attributeName = 'data-tag';
    translate.init(attributeName, currentLng);
    translate.process(); 
 }
</script>
 
 <style>
     form{
         width : 320px;
         border-style : solid;
         border-size : 1px;
         border-color: lightgrey;
         padding:5px;
     }
    .hSpace{
         display: inline-block;
         width:150px !important;         
    }
 </style>
<body onload="load()"> 

 <form>
    <center><h2><label data-tag="contact"> 
    </label></h2></center>
     <div>
        <label class="hSpace" data-tag="email"> 
        </label>:<input type="text" />
     </div>
     <div>
        <label class="hSpace" data-tag="password">
        </label>:<input type="text" />
     </div>
     <div>
        <label class="hSpace" data-tag="subject">
        </label>:<input type="text" />
     </div>
     <div>
        <label class="hSpace" data-tag="message">
        </label>:<input type="text" />
     </div>
 </form>
 
 </body>
</html>

Points of Interest

I hope you appreciated this post. Try to download the source code. Please post your questions and comments below.

History

  • v1 13/01/2017: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
France France
Microsoft certified professional in C# ,HTML 5 & CSS3 and JavaScript, Asp.net, and Microsoft Azure.

Comments and Discussions

 
SuggestionSwitch between languages Pin
Netflex Codes9-Jan-21 12:56
Netflex Codes9-Jan-21 12:56 
QuestionCode given Pin
Member 145749421-Sep-19 23:07
Member 145749421-Sep-19 23:07 
QuestionSome considerations Pin
csorin16-Jan-17 8:16
csorin16-Jan-17 8:16 
AnswerRe: Some considerations Pin
O.Nasri16-Jan-17 9:26
professionalO.Nasri16-Jan-17 9:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.