Skip to content Skip to sidebar Skip to footer

Javascript/Jquery Call Google Translate On Button Click (with Flags)

Is there any good example where I can use Google Translate for translations inside html page? I mean, if I click on german flag (button) than translate to german etc... My question

Solution 1:

You can hide this auto-created selection-field and set it's value dynamically by iterating over each option-field to search for the desired language that you can choose via an input-field.

Hope this helps:

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

<h1>My Web Page</h1>

<p>Hello everybody!</p>

<p>Translate this page.</p>

<!-- hide auto-created selection field completely by hiding it's container -->
<div id="google_translate_element" style="display:none"></div>

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

<!-- flag: you can choose language here: en, de, af etc. -->
<input value="en" id="language"/>
<button onclick="changeLanguageByButtonClick()">Translate</button>

</body>
<script type="text/javascript">

function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: "en"}, 'google_translate_element');
}

function changeLanguageByButtonClick() {
  var language = document.getElementById("language").value;
  var selectField = document.querySelector("#google_translate_element select");
  for(var i=0; i < selectField.children.length; i++){
    var option = selectField.children[i];
    // find desired langauge and change the former language of the hidden selection-field 
    if(option.value==language){
       selectField.selectedIndex = i;
       // trigger change event afterwards to make google-lib translate this side
       selectField.dispatchEvent(new Event('change'));
       break;
    }
  }
}
</script>

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

</html>

Post a Comment for "Javascript/Jquery Call Google Translate On Button Click (with Flags)"