how to build multiple language website using pure html, js, jquery?

Laodao picture Laodao · Sep 2, 2017 · Viewed 49.6k times · Source

i am using html to build pages. The problem is how to build multiple language switch? Language translate is not issue, i have the terms. However, I don't know how to switch btw every page through the language button/dropdown list on the menu bar? If there is a existing example or template, that would be even better. Thanks in advance.

Answer

M. Waheed picture M. Waheed · Sep 2, 2017

ok. as an edit to the my answer, please follow:

1 - create a folder called language and add 2 files to it ( es.json and en.json )

The json files should be identical in structure but different in translation as below:

en.json

{ 
    "date": "Date", 
    "save": "Save",
    "cancel": "Cancel" 
}

es.json

{ 
    "date": "Fecha", 
    "save": "Salvar",
    "cancel": "Cancelar" 
}

2 - Create an html page containing a sample div and put 2 links to select the language pointing to the js function listed in step 3.

<a href="#" onclick="setLanguage('en')">English</a> 
<a href="#" onclick="setLanguage('es')">Spanish</a>

<div id="div1"></div>

3 - Create 2 java script functions to get/set the selected language:

<script>
var language; 
function getLanguage() {
(localStorage.getItem('language') == null) ? setLanguage('en') : false;
$.ajax({ 
url:  '/language/' +  localStorage.getItem('language') + '.json', 
dataType: 'json', async: false, dataType: 'json', 
success: function (lang) { language = lang } });
}

function setLanguage(lang) {
localStorage.setItem('language', lang);
}
</script>

4 - Use the variable language to populate the text.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>

    $(document).ready(function(){
    $('#div1').text(language.date);
    });

    </script>

I believe this answers the question as I have the same concept implemented cross multiple sites.

Note: You can make instant translation ( without reload ) just by using an onclick event other than document.ready from JQuery. It depends on your scenario.