Translate Web Content Using Google Translate API

Translate Web Content Using Google Translate API
File Size: 3.87 KB
Views Total: 131
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

This is a small jQuery script that leverages Google Cloud Translation API to translate web content between languages by selecting a country from a dropdown select containing all supported languages with flags.

How to use it:

1. Create a country list containing languages from which you can choose to translate your webpage. You need to load the following resources if you want to display flags at the beginning of the country names.

<!-- jQuery Is Required -->
<script src="/path/to/cdn/jquery.slim.min.js"></script>

<!-- Bootstrap -->
<link rel="stylesheet" href="/path/to/cdn/bootstrap.min.css" />
<script src="/path/to/cdn/bootstrap.min.js"></script>

<!-- Bootstrap Select -->
<link rel="stylesheet" href="/path/to/cdn/bootstrap-select.min.css" />
<script src="/path/to/cdn/bootstrap-select.min.js"></script>

<!-- Flag Icon -->
<link rel="stylesheet" href="/path/to/cdn/flag-icon.min.css" />
<select class="selectpicker" data-width="fit" onchange="translateLanguage(this.value);">
  <option data-content='<span class="flag-icon flag-icon-af"></span> Afrikaans' value="Afrikaans">Afrikaans</option>
  <option  data-content='<span class="flag-icon flag-icon-al"></span> Albanian' value="Albanian">Albanian</option>
  <option  data-content='<span class="flag-icon flag-icon-ar"></span> Arabic' value="Arabic">Arabic</option>
  <option  data-content='<span class="flag-icon flag-icon-am"></span> Armenian' value="Armenian">Armenian</option>
  <option  data-content='<span class="flag-icon flag-icon-az"></span> Azerbaijani' value="Azerbaijani">Azerbaijani</option>
  ...
</select>

2. Load the needed Google Translate API.

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

3. Add the Google Translator Widget to the page.

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

4. The main script to enable the Google Translator on your webpage.

function googleTranslateElementInit() {
  new google.translate.TranslateElement({ pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false }, 'google_translate_element');
}

function translateLanguage(lang) {
  googleTranslateElementInit();
  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;
}

$(function(){
  $('.selectpicker').selectpicker();
});

This awesome jQuery plugin is developed by devdreamsolution. For more Advanced Usages, please check the demo page or visit the official website.