Adding Google Translate to a Web Site

Adding a translation option to website

The typical approach to this is to have the content swap out based on some toggle - as in your example site - or indicator in the url - such as example.uk or example.de.

This would be much more efficient than attempting to translate your content for users with some widget, because it needs to be translated only once rather than every time a user visits the content.

There are also built-in translation features for certain browsers, chrome in particular often offers to translate pages. You can help enhance this a bit by explicitly stating what language your website is in, and then Chrome will offer to translate it to the language of the user's browser for them; there are two main ways to do this:

W3C recommends using the lang and/or xml:lang attributes in the html tag:

<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">

Google recommends the meta http-equiv:

<meta http-equiv="Content-Language" content="en">

Adding Google Translate to a web site

Here's the markup that should work, both locally and remotely - copied from https://www.w3schools.com/howto/howto_google_translate.asp:

<div id="google_translate_element"></div>
<script>
function googleTranslateElementInit() {
new google.translate.TranslateElement(
{pageLanguage: 'en'},
'google_translate_element'
);
}
</script>
<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Implementing Google Translate with custom flag icons

Had a lot of fun finding a solution for this question!

<!-- Use CSS to replace link text with flag icons -->
<ul class="translation-links">
<li><a href="#" class="spanish" data-lang="Spanish">Spanish</a></li>
<li><a href="#" class="german" data-lang="German">German</a></li>
</ul>

<!-- Code provided by Google -->
<div id="google_translate_element"></div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false}, 'google_translate_element');
}
</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript"></script>

<!-- Flag click handler -->
<script type="text/javascript">
$('.translation-links a').click(function() {
var lang = $(this).data('lang');
var $frame = $('.goog-te-menu-frame:first');
if (!$frame.size()) {
alert("Error: Could not find Google translate frame.");
return false;
}
$frame.contents().find('.goog-te-menu2-item span.text:contains('+lang+')').get(0).click();
return false;
});
</script>


Related Topics



Leave a reply



Submit