Using JavaScript to Change Website Language

Using Javascript to change website language

You can use data attributes: the fact that "HTML5 attributes are not supported in IE6 and IE7" means that you don't get the getAttribute() method or the dataset property for retrieving/accessing them. But you can still retrieve them as explained in this post.

<div id="geoff" data-geoff="geoff">
var geoff = document.getElementById("geoff");
alert(geoff.getAttribute("data-geoff"));

Even better, you can use jQuery .data() to support previous versions of IE.

Something along these lines should work:

<div data-translate="translation_key"></div>
$("[data-translate]").each(function(){
var key = $(this).data('translate');
$(this).html(dictionary[key][current_lang] || "N/A");
});

Working example: https://jsfiddle.net/x93oLad8/4/

Change HTML Page Language

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>

How can I change the language of the website using Javascript?

Please look up i18n for best js translation

How to change a HTML page into a different language?

Level entry internationalization is achieved by using style properties:

function changeLanguage(languageCode) {
Array.from(document.getElementsByClassName('lang')).forEach(function (elem) {
if (elem.classList.contains('lang-' + languageCode)) {
elem.style.display = 'initial';
}
else {
elem.style.display = 'none';
}
});
}

// select handler
const selector = document.getElementById('langSelector');
selector.addEventListener('change', function (evt) {
changeLanguage(this.value);
});

// detect initial browser language
const lang = navigator.userLanguage || navigator.language || 'en-EN';
const startLang = Array.from(selector.options).map(opt => opt.value).find(val => lang.includes(val)) || 'en';
changeLanguage(startLang);

// updating select with start value
selector.selectedIndex = Array.from(selector.options).map(opt => opt.value).indexOf(startLang)

// fill "The selected language is:"
document.getElementById('browserLang').innerText = lang;
document.getElementById('startLang').innerText = startLang;
<div>
<p class="lang lang-en">My english text</p>
<p class="lang lang-de">Mein deutscher Text</p>
<p class="lang lang-it">Il mio testo</p>
<p class="lang lang-es">El mi texto</p>
<p class="lang lang-zh">我的文字</p>
</div>
<select id="langSelector">
<option value="en">English</option>
<option value="it">Italian</option>
<option value="es">Espanol</option>
<option value="de">Dutch</option>
<option value="zh">Chinese</option>
</select>
<div>
<p>Your browser language is: <b id="browserLang"></b></p>
<p>The selected language is: <b id="startLang"></b></p>
</div>

Language change on website best way

Dump all the content of the page to a string or some data structure and then by using the module "translate" you can translate it to any other language. It provides translation to multiple languages then on button click translate the text and send back as response and set the text on the client side. You can install it by:-

 npm install --save translate

A sample code for that will be:-

// 'es' can be a language string or an object like { to: 'es' }
translate('Hello world', 'es').then(text => {
console.log(text); // Hola mundo
});

You can find more help here:-

  https://www.npmjs.com/package/translate

Switch language depends on user's browser or OS system language

Ok, I found an answer.

Simple JS to it.

let language = window.navigator.language;
let languageFistTwo = language.substr(0, 2); // To only keep the first 2 characters.
let currentLocation = document
.getElementsByTagName("html")[0]
.getAttribute("lang-js");

switch (languageFistTwo) {
case "it":
if (currentLocation == "it") window.location.href = "../../index-test.html";
break;

default:
if (currentLocation != "en") {
window.location.href = "../../index.html";
}
}

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

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.



Related Topics



Leave a reply



Submit