I am trying to create a Button to translate my website to Spanish. I am using the already provided code by google, but the issue with the code is that it creates a drop down menu to select Spanish language. I want the website to be translated after clicking down the button without having to use the dropdown menu.
<div id="google_translate_element"></div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'es', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
The code above creates the dropdown menu in order to select Spanish instead of using the button to automatically translate the page. See below for a screenshot of the button and dropdown selector.
I already tried creating the button using the onclick parameter in order to call the googleTranslateElementInit()
fuction, but is not working
<button type="button" class="button" id="clickMe" onclick="googleTranslateElementInit()">Español</button>
2
Answers
I was able to find and answer to my question here in stackoverflow even when I have not idea how it works.
This answer https://stackoverflow.com/a/66887084/22348584 which uses Country flags halped me to solve my problem. Only thing I did was to use my already created button instead of a flag, edit the language to "('en|es')" and now everytime I click the buttom the website gets translated to Spanish.
We have to work with what layouts google translate API offers us, unfortunately they all seem to be dropdowns.
But as a workaround we can try to build on top of what you already did with your button. Instead of the button onClick even handler as googleTranslateElementInit(), try to create a separate handler that translates the page into Spanish like:
And attach it to your button onClick event like: