DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Benjamin Delespierre
Benjamin Delespierre

Posted on

How to add basic localization to your HTML page with just jQuery

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>
Enter fullscreen mode Exit fullscreen mode

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))
}
Enter fullscreen mode Exit fullscreen mode

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)

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!