Skip to content

Instantly share code, notes, and snippets.

@gengns
Last active August 10, 2018 12:38
Show Gist options
  • Save gengns/98aa19d27e929c6c7d964ffbf6eb69b0 to your computer and use it in GitHub Desktop.
Save gengns/98aa19d27e929c6c7d964ffbf6eb69b0 to your computer and use it in GitHub Desktop.
Basic translator using Vanilla JavaScript
If you want to test it locally:
chromium-browser --allow-file-access-from-files
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<label class="T">Usuario</label>
<label class="T">Contraseña</label>
<select>
<option value="es">Español</option>
<option value="en">English</option>
<option value="fr">Français</option>
</select>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="index.js"></script>
</body>
</html>
// Translator
let T_ = txt => txt
// Default language
if (!localStorage.lang) localStorage.lang = navigator.language.slice(0, 2)
// Default selection
if (localStorage.lang != 'es') {
document.querySelector('select').value = localStorage.lang
language_update(localStorage.lang)
}
// Changes selection
document.querySelector('select').onchange = e => {
localStorage.lang = e.target.value
location.reload()
}
// Loads file and updates translation
function language_update(lang) {
axios.get(`language.${lang}.json`)
.then(r => {
// If there is not translation, we will return the current text
T_ = txt => r.data && r.data[txt] ? r.data[txt] : txt
// Translates all text content with T class
document.querySelectorAll('.T')
.forEach(e => e.textContent = T_(e.textContent))
})
}
{
"Usuario": "User",
"Contraseña": "Password"
}
{
"Usuario": "Utilisateur",
"Contraseña": "Mot de passe"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment