I'm trying to implement a Multi-language for one website. I prefer to use client script for changing the language between English
and Traditional Chinese
.
For example:
Create a client script to get/set the selected language:
$(document).ready(function() {
// The default language is English
var lang = "en-gb";
$(".lang").each(function(index, element) {
$(this).text(arrLang[lang][$(this).attr("key")]);
});
});
// get/set the selected language
$(".translate").click(function() {
var lang = $(this).attr("id");
$(".lang").each(function(index, element) {
$(this).text(arrLang[lang][$(this).attr("key")]);
});
});
Then, build multiple languages dictionary to JSON structure:
var arrLang = {
"en-gb": {
"HOME": "Home",
"ABOUT": "About Us",
"CONTACT": "Contact Us",
},
"zh-tw": {
"HOME": "首頁",
"ABOUT": "關於我們",
"CONTACT": "聯絡我們",
}
};
Here's my HTML page:
<button class="translate" id="en-gb">English</button>
<button class="translate" id="zh-tw">Chinese</button>
<ul>
<li class="lang" key="HOME"></li>
<li class="lang" key="ABOUT"></li>
<li class="lang" key="CONTACT"></li>
</ul>
A part of the code is shown below:
var arrLang = {
"en-gb": {
"HOME": "Home",
"ABOUT": "About Us",
"CONTACT": "Contact Us",
},
"zh-tw": {
"HOME": "首頁",
"ABOUT": "關於我們",
"CONTACT": "聯絡我們",
}
};
$(document).ready(function() {
// The default language is English
var lang = "en-gb";
$(".lang").each(function(index, element) {
$(this).text(arrLang[lang][$(this).attr("key")]);
});
});
// get/set the selected language
$(".translate").click(function() {
var lang = $(this).attr("id");
$(".lang").each(function(index, element) {
$(this).text(arrLang[lang][$(this).attr("key")]);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="translate" id="en-gb">English</button>
<button class="translate" id="zh-tw">Chinese</button>
<ul>
<li class="lang" key="HOME"></li>
<li class="lang" key="ABOUT"></li>
<li class="lang" key="CONTACT"></li>
</ul>
However, When I refresh the page or navigate to another page it returns to the original language. Is there any way to keep the selected language even by refreshing the page?
Thank you!