Using JavaScript to Translate Your Static Website

Define key value pairs of text translation in json file
3 months ago SETHA THAY 336
Using JavaScript to Translate Your Static Website

A static website contains web pages with fixed content. each page is coded in HTML and displays the same information to every visitor. A static site can be built by simply creating a few HTML pages and publishing them to a Web server.

Since static Web pages contain fixed code, the content of each page does not change unless it is manually updated by the webmaster. This works well for small websites such as personal portfolios or curriculum vitae which are not frequently updated. Most of the static website templates found in google mostly are in the English language, which is not so useful if you want to make your website locales. 

using-javascript-to-translate-your-static-website-sample

In this post, I would like to introduce a snippet of JavaScript code that can translate all the English words inside your website into any language you want. In this technique, you just need to define your wording translation in a JSON file and include the JavaScript code into your website it will work like a charm.

STEP 1: Create Translation Function

Let create a new JavaScript file called "translate.js" and then write code to get translation text from JSON file in folder lng based on the selected language.

 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", "lng/"+this.lng+".json", false);
		xrhFile.onreadystatechange = function ()
		{
			if(xrhFile.readyState === 4)
			{
				if(xrhFile.status === 200 || xrhFile.status == 0)
				{
					var LngObject = JSON.parse(xrhFile.responseText);
					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) {
							elem.innerHTML = LngObject[key]  ;
						}
					}
				
				}
			}
		}
		xrhFile.send();
    }
}

STEP 2: Switch Language Function

Create a new JavaScript file named "index.js" to begin the translation process

//This function will be called when user click changing language
function translate(lng, tagAttr){
    var translate = new Translate();
    translate.init(tagAttr, lng);
    translate.process();
    if(lng == 'en'){
      $("#enTranslator").css('color', '#f4623a');
      $("#khTranslator").css('color', '#212529');
    } 
    if(lng == 'kh'){
      $("#khTranslator").css('color', '#f4623a');
      $("#enTranslator").css('color', '#212529');
    }
}
$(document).ready(function(){
  //This is id of HTML element (English) with attribute lng-tag
  $("#enTranslator").click(function(){
    translate('en', 'lng-tag');
  });
  //This is id of HTML element (Khmer) with attribute lng-tag
  $("#khTranslator").click(function(){
    translate('kh', 'lng-tag');
  });
});

STEP 3: Define Your Translation Text in JSON

Let define translation text in JSON file as below

using-javascript-to-translate-your-static-website-json-file

STEP 4: Embed Translation into Your Website

  • Import both JavaScript file "index.js" and "translate.js" to HTML page
<script src="js/translate.js"></script>
<script src="js/index.js"></script>
  • Set selected language when first loading the page
<body id="page-top" onload="translate('kh','lng-tag')">
  • Define HTML element with attribute "lng-tag" for the text you wanted to be translated and value of attribute is the key which define in JSON file

using-javascript-to-translate-your-static-website-attribute-to-be-translate

Here is the static website which implements the above method to translate language between Khmer (CAMBODIAN) and English https://praject.co/

 

THANK YOU


About author

Author Profile

SETHA THAY

Coding lover. I am willing to share my knowledge and 10 years experiences in the IT field. Please feel free to feedback on my post if you found any problems. Thank You.


DigitalOcean Referral Badge

Scroll to Top