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><htmllang="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 --><divid="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. --><inputvalue="en"id="language"/><buttononclick="changeLanguageByButtonClick()">Translate</button></body><scripttype="text/javascript">functiongoogleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: "en"}, 'google_translate_element');
}

functionchangeLanguageByButtonClick() {
  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(newEvent('change'));
       break;
    }
  }
}
</script><scripttype="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)"