If you prefer not to rely on plugins and only need to translate the textual content, consider creating a small dictionary for your page. This method can handle HTML as well.
To simulate the onload function with a toggle button, you can use this function anywhere in your code where the dict object and lang variable are accessible.
The essential markup requirement is the data-translate attribute on the text-containing element and an entry in the dict object.
const dict = {
"0": {
en: "Download - Document",
fr: "Télécharger - Document"
},
"1": {
en: "It's not a document",
fr: "Ce n'est pas un document"
},
"2": {
en: "Translate this, while you<br />are fast asleep.",
fr: "Traduisez ceci pendant que<br />vous êtes endormi."
}
}
let lang = 'en'
const btnLang = document.getElementById('toggleLang')
// click event: toggle language
btnLang.addEventListener('click', function(e) {
lang = lang === 'en' ? 'fr' : 'en'
toggleLang(lang)
})
// toggle language (using lang variable and dict object)
function toggleLang(lang) {
const toTranslate = document.querySelectorAll("[data-translate]")
toTranslate.forEach(e => {
e.innerHTML = dict[e.getAttribute('data-translate')][lang]
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Onload this document will Translate to French.<br><br>
<button id="toggleLang">Toggle language</button>
<div data-translate="0">Download - Document</div><br><br>
<div data-translate="1">It's not a document</div><br><br>
<div data-translate="2">Translate this, while you<br />are fast asleep.</div>
While this solution is simple and lightweight in terms of file size, it has its limitations. You must ensure that the dict object contains all elements referenced in the HTML and that each item includes all the desired language variations.
For a more comprehensive approach, consider exploring i18n for jQuery (, or ). i18n follows internationalization standards and is widely used in platforms like Wordpress (WPML), JS frameworks (such as VueJS: https://www.npmjs.com/package/vue-i18n). By familiarizing yourself with it now, you may find it beneficial for future projects. :)