For a "pure JS" solution, in other words none of the usual solutions:
- no Ajax to get the translated page text / replacement html
- no redirect to a different page which can handle layout incongruities
one option is to store the translations on each div and switch them over using .text(). Do not code your translations into your javascript as that will quickly become impossible to maintain.
function switchLang(lang)
{
$("[data-" + lang + "]").text(function(i, e) {
return $(this).data(lang);
});
}
switchLang("en");
$(".switchlang").click(function() {
// change the button caption here, eg a flag
// UX opinion of whether it should be what it is
// or what it will become
// ie "de" click to make it "de"
// or "de" it's currently "de", click to change it
$(this).text($(this).data("lang"));
// switch to other language based on language on the button
var lang = $(this).data("lang") == "de" ? "en" : "de";
$(this).data("lang", lang);
switchLang(lang)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-de="Um die Nachrichten zu lesen"
data-en="To read the news"></span>,
<span data-de="Übersetzungsdienst nicht verfügbar"
data-en="click here"></span>
<hr/>
<div data-en="no de translation for this line"></div>
<hr/>
<button class='switchlang' data-lang="en">de</button>
You can then easily add new languages without needing to change any code (this time with separate buttons)
var defaultlang = "en";
function switchLang(lang)
{
$("[data-" + lang + "]").text(function(i, e) {
return $(this).data(lang);
});
}
switchLang("en");
$(".switchlang").click(function() {
switchLang($(this).data("lang"))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-de="Um die Nachrichten zu lesen"
data-es="Para leer las noticias"
data-en="To read the news"></span>,
<span data-de="Übersetzungsdienst nicht verfügbar"
data-es="haga clic aquí"
data-en="click here"></span>
<hr/>
<div data-es="no hay traducción para esta línea"
data-en="no de translation for this line"></div>
<hr/>
<button class='switchlang' data-lang="en">en</button>
<button class='switchlang' data-lang="de">de</button>
<button class='switchlang' data-lang="es">es</button>
You may prefer to default the language in the HTML directly, rather than on startup, eg:
<span data-de="speichern">save</span>
then store the original in .data("en") on load. This would remove the FOUC (delay when loading the page) which may be important for your scenario.
data-[lang]attribute is that you send the text to the client only in the required language and the system is easier to scale (in case you think you might add new languages in the future).