Translate Content with the Google Translate API and JavaScript

By  on  

Note:  For this tutorial, I'm using version1 of the Google Translate API.  A newer REST-based version is available.

In an ideal world, all websites would have a feature that allowed the user to translate a website into their native language (or even more ideally, translation would be done before the user sees anything on the page).  In the real world, most small businesses can't afford to invest money into website translation.   Luckily a small startup named "Google" provides an outstanding Translate API to translate simple text from one language to another!

Sample HTML

Google's awesome Translate API allows you to send HTML -- you don't need to extract the text yourself! That's a huge feature because parsing HTML and putting it all back again would be a nightmare!  Let's put together some sample content:

<script src="https://www.google.com/jsapi?key=YOUR_GOOGLE_KEY"></script>
<div id="languages"><p>
	<a href="?lang=en" rel="en">English</a> / <a href="?lang=es" rel="es">Spanish</a> / <a href="?lang=it" rel="it">Italian</a> /
	<a href="?lang=fr" rel="fr">French</a>
</p></div>

<div id="languageBlock">
	<p>Lights go out and I can't be saved <br />
	Tides that I tried to swim against  <br />
	Brought me down upon my knees  <br />
	Oh I beg, I beg and plead </p>

	<p>Singin', come out if things aren't said  <br />
	Shoot an apple off my head  <br />
	And a, trouble that can't be named  <br />
	Tigers waitin' to be tamed </p>

	<p>Singing, yooooooooooooo ohhhhhh  <br />
	Yoooooooooooo ohhhhhh </p>

	<p>Home, home, where I wanted to go <br /> 
	Home, home, where I wanted to go  <br />
	Home, home, where I wanted to go  <br />
	Home, home, where I wanted to go</p>
</div>

We will use this #languageBlock element to send to Google for translation.  Note that each link has a rel attribute which holds the code for the language to switch to.

Google Translate API JavaScript

For the sake of keeping the code short, I'm using MooTools to access elements and add DOM events.  Feel free to stick to simple JavaScript or your framework of choice.

// Set the original/default language
var lang = "en";
var currentClass = "currentLang";

// Load the language lib
google.load("language",1);

// When the DOM is ready....
window.addEvent("domready",function(){
	// Retrieve the DIV to be translated.
	var translateDiv = document.id("languageBlock");
	// Define a function to switch from the currentlanguage to another
	var callback = function(result) {
		if(result.translation) {
			translateDiv.set("html",result.translation);
		}
	};
	// Add a click listener to update the DIV
	$$("#languages a").addEvent("click",function(e) {
		// Stop the event
		if(e) e.stop();
		// Get the "to" language
		var toLang = this.get("rel");
		// Set the translation into motion
		google.language.translate(translateDiv.get("html"),lang,toLang,callback);
		// Set the new language
		lang = toLang;
		// Add class to current
		this.getSiblings().removeClass(currentClass);
		this.addClass(currentClass);
	});
});

The first step in the process is using google.load to load the Translate API.  When the the API is loaded, we grab the DIV to be translated.  We then define a callback for when the translation returns from Google.  This callback simply updates the content of the DIV.  The last step is adding a click event handler to each language link.  A google.language.translate call sends the content to Google for translation.  When the translated content returns, the content is updated by our callback!

Thanks to Google's Translate API, we can effortlessly translate data!  It's important that I note that Google's content size limit is quite small so you shouldn't rely on the Translate API to completely translate your a page.  It is, however, an excellent way to translate an alert or status message in a give language!

Recent Features

  • By
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

Incredible Demos

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

  • By
    Create a Download Package Using MooTools Moousture

    Zohaib Sibt-e-Hassan recently released a great mouse gestures library for MooTools called Moousture. Moousture allows you to trigger functionality by moving your mouse in specified custom patterns. Too illustrate Moousture's value, I've created an image download builder using Mooustures and PHP. The XHTML We provide...

Discussion

  1. Alelo

    french but no german? :(

    but nice article again :)

  2. Can the Google API automatically detect the original/default language as it does at http://translate.google.com/ ?

    Maybe instead of
    var lang = “en”;
    we could have
    var lang = “auto”;

    It could save us some time :P

    • Patrick

      Yes, it called ‘Detecting language type’ in Google API speak. If you browse to the API site you can read about how to implement the method. You can set it to return either the language 2 character code or the language name (depending on what you need for your solution).

  3. Burak Erdem

    Great article. I wish you had written that article a year ago, while we were trying to implement Google Translate into an instant messaging application for one of our clients. That would have saved lots of my time :( Thanks anyway for that wonderful article.

  4. Thanks for the post. Google makes everything so much easier :)

  5. Gotta love Google. Did not realize they had API for this.
    Thats pretty cool.

    @David, where you have the get HTML content, could this be used for say the BODY or would that just take too long to translate?

    • That request would be far too large, unfortunately. Google’s Translate API is not a complete website translation service.

    • Bob Lindabury

      Actually, you can translate a whole website, page-by-page, with Google’s Translate API using jquery-translate. I’ve done it for a portion of one of our products. You can select elements to translate and to NOT translate if you wish. It will also translate comments if you tell it to.

      Here’s what it says about the jquery plugin:

      “This plugin integrates the Google Ajax Language API to jQuery. You can just call e.g. $('body').translate('en') but provides callbacks for each translated element too. Or you can pass an array to $.translate to get back a translated array. Currently you can only send a limited amount of characters with the raw API per request but this plugin calls them consecutively. It also reduces the number of requests by concatenating elements and doesn’t send unnecessary html markup still providing access to each element as they’ve got translated.”

      You can find this at: http://code.google.com/p/jquery-translate/

      Enjoy!

      — Bob

  6. Vasilis Komianos

    Very usefull post, thanks a lot. I was thinking to use google’s translate API on a project and i was wondering about the limitations it has.
    Is there any service, even if it has to be paid, for translation?

  7. Very useful and interesting post, thanks David, we now just have to wait for google being able to make accurate translation though!!

  8. Sarath Dontireddy

    Pretty useful!Thanks for sharing!!!

  9. There sure are a lot! Of exclamation points!

    On this page!!!!

  10. Ozzy

    Interesting, but the translations are somewhat… crappy.
    Not meaning to criticize, knowing it’s free and so, but all in all it’s not actually a reliable service for any serious project.
    Also, there is the google plug-in that does the same job automatically without having to write any code at all.

    • Grant

      Ozzy,

      There is a simple version of this. The only problem I found with it is that it creates a 40px space at the top of the page for it’s toolbar when you translate, and that screws up my formatting.

      http://translate.google.com/translate_tools

  11. Ashenafi D.

    Nice One, greatful that you shared it!

  12. Does Google Translate’s API provide translation for ajax based content? Meaning if the user made a selection on a translated page and the call brought back additional information through ajax, would that content be translated when it came back?

    Thanks!

  13. Frankie

    I cannot get this to work properly. I copied the code pasted it into an HTML page and changed the API section to my API but its not working.

    JS is refreshing the page rather than doing the functions without page refresh like the demo. Can anyone help?

  14. merakli

    Is there a character limit?
    I think because there is no such restriction, so long does not make a text translation

    what is Default limit characters/day ?

  15. mahi

    Hi,i use the above code in html tag.But not any changes occur when try to convert into another language.So please anybody help me.please tell me if any file or api use for that purpose.

  16. Google Translate API expire 2011-12-01 :-(

  17. Dear David, Thank you for the beautiful post, is there a way where you can post a new article on how to implement Google Translate Api v2. For genius like you it wont take more than a few hrs. I am stuck on it since 3 days.

    Plz help bro.

  18. dinesh

    I want to change only some part of the webpage like that

    “This is a cat” and i want to change CAT into another language in php This is not change only cat word change in to another language.

    pls help on this topic.

    thanks

  19. Shafiq

    Code does not work anymore . Can some one revise it please ?

  20. Rehman

    Google Translate API 2 came out

    need a tutorial for API2 in javascript

  21. API2, can anyone post guide how to integrate?

  22. Hsn

    Hello David Walsh,
    your tutorial is good and working.
    I added more languages but they are not working all,
    you can only 4 tries to change language after that there is nothing happened.
    its no matter where from you start even from start or randomize.
    but only 4 tries work after that you have to reload the page.
    please give any solution for this. :(

  23. The demo is not working for only me? I don’t see any JS errors in the browser console though. Not sure if the library that the demo is using, has been deprecated by Google. Can someone throw some light on this, please?

  24. Nurul

    Hi there! Sorry but why can’t I click in the link in demo to change the language?

  25. ammar

    Demo is not working. Response from google api is saying upgrade to v2. Please update it.

  26. Dave

    Hi there! For any software translation project, I recommend trying https://poeditor.com/ which is a great localization tool, well designed for users, featuring a very flexible and intuitive work interface.

  27. Since, this article is written in 2011, So wat is the best way to convert site from one language to another in 2017?

  28. Hasan

    Hey everyone, Google has released its API v2 and this article is for v1 so it’s not working. The v2 API is paid now, so you have to pay for it.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!