[MultiLang] How to Create a Multilingual Application using JavaScript

https://www.codeproject.com/Tips/1165561/How-to-Create-a-Multilingual-Application-using-Jav

C:\xampp\htdocs\windows\index.html

<!DOCTYPE html>
<html>
<script src="translate.js"></script>
<script type="text/javascript">
  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>

C:\xampp\htdocs\windows\translate.js

 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();
   }
 }

C:\xampp\htdocs\windows\resources\en.json

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

C:\xampp\htdocs\windows\resources\fr.json

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

Last updated

Navigation

Lionel

@Copyright 2023