A simple web component for translating text content in HTML pages.
Author your HTML content in any language. Mark the translatable sections with the lang attribute. Create a JSON file for translations. Add the web component to your page, and it will render a language switcher element for the languages found.
ul/li list?lang=en)1. Include the CSS and JavaScript files in your HTML:
<script src="https://unpkg.com/translate-element/translate-element.js"></script>
2. Add the translate element to your page:
<translate-element></translate-element>
3. Optionally, style the language switcher element using CSS:
<link rel="stylesheet" href="translate-element.css">
You can use translate-element.css as an example.
Mark elements for translation by adding the lang attribute with your default language:
<h1 lang="en">Welcome</h1>
<p lang="en">This is a sample paragraph.</p>
<input type="submit" value="Submit" lang="en">
<input type="text" placeholder="Enter your name" lang="en">
<button lang="en">Click Me</button>
If an element has the lang attribute, the following attributes are translated: alt, cite, href, label, placeholder, src, srcset, title, value.
<img src="image.jpg" alt="Sample image" lang="en">
<a href="/contact" title="Contact us" lang="en">Contact</a>
You can maintain the translations directly within your HTML:
<h1 lang="en">Welcome</h1>
<h1 lang="de">Willkommen</h1>
<p lang="en">This is a sample paragraph.</p>
<p lang="de">Dies ist ein Beispielabsatz.</p>
Create a JSON file with your translations. First level keys are the textContent of the elements to translate. The values are objects with a language codes as keys and corresponding translations as values. Example:
{
"Text to translate": {
"fi": "Käännettävä teksti",
"sv": "Text att översätta",
"de": "Text zu übersetz"
},
"Welcome": {
"fi": "Tervetuloa",
"sv": "Välkommen",
"de": "Willkommen"
}
}
Refer to the translation file in your HTML:
<translate-element src="translations.json"></translate-element>
If the HTML content contains an element with the lang attribute, but no translations are found in the translations.json file, the web component will output the textContent of the untranslated element into the developer console.
| HTML | translations.json |
|---|---|
|
|