I want basic translation on my single, static HTML page but I don't want to import no complex JS lib... What do I do?
Very simple my friend
HTML structure
<html lang="en">
<body>
<p lang="en">English please!</p>
<p lang="fr">Hon hon croissant baguette!</p>
<button type="button" lang="fr" data-toggle="lang" data-lang="en">English</button>
<button type="button" lang="en" data-toggle="lang" data-lang="fr">Français</button>
<script src="jquery.js"></script>
<script src="language.js"></script>
</body>
</html>
Go get jQuery here. If you don't want it I think you can make your own vanilla version of the script below.
The JS script
$('[data-toggle="lang"]').click(function(event) {
event.preventDefault();
$('html').attr('lang', $(this).attr('data-lang'));
});
// auto-detect the best lang setting
const params = new URLSearchParams(window.location.search);
if (params.has('lang')) {
$('html').attr('lang', params.get('lang'));
} else if (navigator.language.match(/^(en|fr)/)) {
$('html').attr('lang', navigator.language.substr(0, 2))
}
That's it. The HTML will now respond to the lang
attribute in the <html>
tag. You can control it adding ?lang=fr
to the URL or let the browser decide with navigator.language
.
Enjoy!
Top comments (0)