Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 762
Laodao Avatar asked Sep 01 '17 22:09

Laodao


People also ask

How do you serve HTML page with content in multiple languages?

To change the language, just simply set the lang attribute. We can define it anywhere in the document, such as in the body, in the paragraph, in the heading, or in the span tag. But the best practice is to set the lang in the span tag.


1 Answers

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.

like image 83
M. Waheed Avatar answered Sep 16 '22 14:09

M. Waheed