Click here to Skip to main content
15,883,901 members
Articles / Web Development / HTML

Translate Website/Webapp with JS/JQuery and XML

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 Jun 2015CPOL3 min read 13.1K   110   1  

Introduction

Having completed a web application, or website, in your native language, comes the necessity to localize it in another language, to make it accessible outside your country too. If you have hard-coded strings in your pages (which you've probably done, especially for labels and/or all-purpose messages), a task like this could be pretty eerie to accomplish (primarily depending on project size, or complexity level).

Here we'll see a fast and easy method to alter a webpage's DOM, using a custom resource file to modify our strings inside predetermined elements. We'll see how to do that using plain Javascript first, then JQuery.

A simple page

Here follows the HTML of a simple page, showing some elements' values written in Italian. Please note all the elements have an ID. That's fundamental for when we come to the scripting part.

HTML
<html>
   <head>
      <title>Translate Website/Webapp with JS and XML</title>
   </head>

   <body>
      <h1 id="AppTitle">Titolo applicazione</h1>
      
      <span id="GenText">Testo generico con fini dimostrativi</span><br/>
      <span id="EndText">Testo di chiusura</span>
      
      <div id="DivText">
         Testo contenuto in un div.
      </div>
   </body>
</html>

Opening it in a browser, our page will resemble the following:

Image 1

Making a string resource file

In an hypothetical string resource file, we want to introduce all of our app's strings. We can create a set of XML entities having attributes complying our HTML elements. In other words, exploiting the javascript function to access DOM's elements by their ID, we could think of pairing a given HTML ID with its XML counterpart. For example, based on the previous page example, we could jot down a resource file like the following:

XML
<strings>
   <string id="AppTitle"     en = "Application's Title"/>
   <string id="GenText"      en = "Generic text with demonstrative means"/>   
   <string id="EndText"      en = "Closing text"/>
   <string id="DivText"      en = "Div contained text"/>
</strings>

For each string entity, we've defined two attributes: the first, id, corresponds to a particular ID in HTML code, while the second one, "en", contains a english translation of our elements. The logic behind this is simple: when our page finish loading, we need a javascript to be fired up in order to read our DOM's IDs, replacing their innerHTML with the one specified in XML "en" attribute.

We'll save the above example as "translate.xml", for further use.

Replace text using Javascript

The first function we'll write down is about reading our XML file, using XMLHttpRequest (or XMLHTTP, if on IE). Check the following:

JavaScript
function loadXMLDoc(filename){
   if (window.XMLHttpRequest){
      xhttp = new XMLHttpRequest();
   } else {
      xhttp = new ActiveXObject("Microsoft.XMLHTTP");
   }
   xhttp.open("GET",filename,false);
   xhttp.send();
   return xhttp.responseXML;
}

It will simply perform a GET request toward the file indicated as parameter, returning its contents. Another function will use it to open "translate.xml" file, reading its string entities, then looping through the DOM's IDs, in order to replace their contents.

JavaScript
function localize(){
   xmlDoc = loadXMLDoc("translate.xml");
    
   var x = xmlDoc.getElementsByTagName("string");
   for (i=0;i<x.length;i++)  {
      var elem = document.getElementById(x[i].getAttribute('id'));
      if (elem!=null) elem.innerText = x[i].getAttribute('en');   
   }      
}

Finally, localize() function must be fired up after the complete load of our page, to ensure all the elements will be rendered/accessible. We could simply add an explicit call to localize() after the closing of body tag, in the following way:

JavaScript
   <!-- omissis -->
   </body>

   <script>
      localize();
   </script>
</html>

You could refer to file "sample01.html" in the source code for the full example. Running our page again, we'll see the text will be replaced:

Image 2

IMPORTANT: It's advisable to run the presented code in a web server environment (IIS or Apache), because the opening of our XML file could end up in a cross origin request exception otherwise.

Image 3

Replace text using JQuery

Using JQuery will result in a more compact script, in which we can rely on asinchronicity and specify to await for complete load in a single location (tipically, HEAD section). The entire script seen above could be replaced with the following:

JavaScript
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
      
<script>
   $(document).ready(function(){
      $.ajax({
         type: "GET" ,
         url: "translate.xml" ,
         success: function(xml) {
             $(xml).find('string').each(function(){
                var item_id = $(this).attr("id");
                $("#" + item_id).text($(this).attr("en"));
             });
         }
      });
   });
</script>

Here, after finishing loading page, our script will proceed in an AJAX call to our trasnalte.xml file, and upon success in accessing it, it will loop through "string" entities, using the "id" and "en" attributes to refer which DOM elements must be targeted, and replacing their inner HTML with the one of our choice. Please refer to "sample02.html" file in the given source code.

Conclusion

Far from declaring the ultimate method to localize a website or webapp, we have seen a pratical and quick method to do that. The quality of such an approach resides indisputably to the minimum interventions needed on the original source code, assuming an ID naming approach has been used in at development stage. Hope you'll find it useful.

History

  • 2015-06-21: First release for CodeProject

License

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


Written By
Software Developer
Italy Italy
Working in IT since 2003 as Software Developer for Essetre Srl, a company in Northern Italy.
I was awarded in 2014, 2015 and 2016 with Microsoft MVP, for Visual Studio and Development Technologies expertise. My technology interests and main skills are in .NET Framework, Visual Basic, Visual C# and SQL Server, but i'm proficient in PHP and MySQL also.

Comments and Discussions

 
-- There are no messages in this forum --