There are plenty of questions likes this, but I've read many of them and what I saw appears to be too complex for my very simplistic case.
I have a super simple one-page website (picstalk.app in case you care). It is nothing more than a few divs with text. I'm looking for the simplest way possible to have that in multiple languages, so that the text with the browser's default language is shown automatically and of course there is a way to switch languages manually.
Ideas?
Thanks.
CodePudding user response:
I'm not sure if this is efficient but since you have very little text, This will work.
// Maintain a supported Language List
var langList = ['en', 'zh'];
// Get browser Language
var userLang = navigator.language || navigator.userLanguage;
// extract Language (en-US => en)
userLang = userLang.substring(0, 2);
// Call the function to set language
changeLang(userLang);
// function to change language
function changeLang(lang) {
langList.forEach((langEle) => {
// if language matches, display
if (langEle == lang) {
var langElems = document.querySelectorAll('.' langEle)
langElems.forEach((elem) => {
elem.style.display = "block"
})
}
// hide the language text
else {
hideLang(langEle)
}
})
}
// function to hide language
function hideLang(lang) {
var langElems = document.querySelectorAll('.' lang)
langElems.forEach((elem) => {
elem.style.display = "none"
})
}
<h1><span lang="en" class="en">Hello</span> <span lang="zh" class="zh">你好</span></h1>
<button onclick="changeLang('en')">English</button><button onclick="changeLang('zh')">Chinese</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You have to use Javascript to do it. At first, you have to create web pages
for different languages
and have a default language
on the landing page
. And then you have to add
a switching button
for users
who want to use your website in their language.