How to Add a Google Translate Button using JavaScript

Updated onbyAlan Morel
How to Add a Google Translate Button using JavaScript

Google Translate is a powerful tool from Google that allows you to translate a web page into any language.

This allows your pages to be more accessible to people who might not speak your language.

In this post, we'll learn how we can use a small amount of JavaScript to add a Google Translate button to our web pages.

How to add a Google Translate button to your web page

To illustrate this example, let's first start with an example HTML page:

HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Google Translate Button</title> </head> <body> <h1>Google Translate Button</h1> <p>This is a paragraph of text.</p> </body> </html>

This is a simple HTML page with a heading and a paragraph of text.

To add a Google Translate button, first we must define where it will live on the page by adding a div element with an id attribute of google-translate-element:

HTML
<div id="google-translate-element"></div>

Now, we must import the Google Translate JavaScript library:

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

Now, we must define a function that will be called when the Google Translate library is loaded.

We can set the page language to English by adding the pageLanguage option:

HTML
<script type="text/javascript"> function googleTranslateElementInit() { new google.translate.TranslateElement({pageLanguage: "en"}, "google-translate-element"); } </script>

Put all of this together to form a single page now:

HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Google Translate Button</title> </head> <body> <h1>Google Translate Button</h1> <p>This is a paragraph of text.</p> <div id="google-translate-element"></div> <script type="text/javascript"> function googleTranslateElementInit() { new google.translate.TranslateElement({pageLanguage: "en"}, "google-translate-element"); } </script> <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script> </body> </html>

When you load this page in your browser, you should see a Google Translate button appear at the bottom of the page, allow you to translate the page into any language.

Conclusion

In this post, we learned how to add a Google Translate button to our web pages using JavaScript.

Simply add a div element with an id attribute of google-translate-element and then import the Google Translate JavaScript library and define a function that will be called when the library is loaded.

That's all there is to it, thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.