I need to replace texts on multiple pages by clicking a simple button. What is the leanest switch between two languages?
This only changes text in the first div. I need to have language change applied across the site.
var text1 = document.getElementById('english');
var text2 = document.getElementById('swedish');
const swap = () => {
if (text1.classList.contains("hidden")) { //if english contains class 'hidden'
text1.classList.remove("hidden"); //remove hidden class from english
text2.classList.add("hidden"); //add hidden class to swedish
} else {
text1.classList.add("hidden"); //add hidden class to english
text2.classList.remove("hidden"); //remove hidden class from swedish
}
}
.hidden {
display: none;
}
<button onclick="swap()">Switch Text</button>
<div class="content">
<div id="english">
<h1>Welcome</h1>
<p>English text</p>
</div>
<div id="swedish" class="hidden">
<h1>Vällkommen</h1>
<p>Svensk tekst</p>
</div>
</div>
2
Answers
lang
as you are supposed toThis script can be included on each page that has the lang set to either languages.
Change the lang to whatever you need. lang="en"/lang="sv" and change the script accordingly
Remove the comments
//
from the lines with localStorage and remove this line on your site: let savedLang = "se_SV";Here is a simple (‘lean’) way to load/show languages. If you need the language to persist, you need to store the selected language. Most convenient is to do that in
localStorage
. That is not supported here, so I created the same snippet in Stackblitz withlocalStorage
to save the selected language.The snippet uses event delegation, data attributes an an
.active
css class to activate/display the right language divs.Or use this factory to switch between two languages.