Home > Mobile >  How can I translate the page with JS?
How can I translate the page with JS?

Time:10-22

I am really new in JavaScript and I was wondering which object on JS I could use to translate (on language) certain identified items when I click a link. For example, when I click a link that says:

Translate to German

All the page will translate to german.

I understand that I can use getElementByID, but I don't really know specifically how.

CodePudding user response:

You can use Google Translate. Here's an example (taken from W3Schools):

<!DOCTYPE html>
<html lang="en-US">
<body>

<h1>My Web Page</h1>

<p>Hello everybody!</p>

<p>Translate this page:</p>

<div id="google_translate_element"></div>

<script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: 'en',
    includedLanguages: 'de,en' // remove this line if you want to include all languages
  },'google_translate_element');
}
</script>

<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

<p>You can translate the content of this page by selecting a language in the select box.</p>

</body>
</html>

See it live here

  • Related