How I translated my portfolio with JavaScript and JSON
A couple of weeks ago, I made a post about language selection and translations (which you should read). So this week, I should make a post about how I translated my personal portfolio website using just vanilla JavaScript.
I mentioned in the other post that here we use i18n to auto-detect the user's language. However, I didn't want to get into any extra trouble on my personal portfolio to have it ready a bit faster and try something new. So, I came up with a straightforward solution using only JavaScript. Let's get into it.
Create an array
I have a really simple array with the IDs assigned to the different strings on my webpage like this:
texts = [
"skillstxt",
"experiencetxt",
"projectstxt",
"title",
];
Create JSONs
Each JSON corresponds to a language, and it has the IDs mentioned with the corresponding string in their language:
en = {
skillstxt: "Skills",
experiencetxt: "Experience",
projectstxt: "Projects",
title: "Software Engineer",
};
es = {
skillstxt: "Habilidades",
experiencetxt: "Experiencia",
projectstxt: "Proyectos",
title: "Ingeniero de software",
};
fr = {
skillstxt: "Compétences",
experiencetxt: "Expérience",
projectstxt: "Projets",
title: "Ingénieur logiciel",
};
Additionally, there is an empty JSON which will then have the translation for the selected language.
The translation function
With the array and the JSONs in place, we can now simply iterate through the array. For each element, we assign the string from the corresponding JSON key to the HTML element:
function translate() {
texts.forEach((t) => {
document.getElementById(t).innerHTML = json[t];
});
}
As mentioned before, if we want to change the language, we just assign the language JSON to the current language JSON and call the translation function to replace the strings in the HTML:
function spanish() {
json = es;
translate();
}
function english() {
json = en;
translate();
}
function french() {
json = fr;
translate();
}
These options are available on the top of my page with each language represented with its ISO code, as mentioned in my previous post, not the best option but helps to save some space.