On a site I tried adding the Google Translate dropdown using the following code:
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'en'
}, 'google_translate_element');
}
<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
When you select from the dropdown that the google script inserts, a Google Translate bar appears at the top of the page, and all text is translated in to the selected language.
However if I try and trigger the dropdown change using JavaScript, it doesn't work:
$('.goog-te-combo').val('fr')
'French' is selected from the dropdown, however Google Translate is not triggered.
Why o why does it not work? I've also tried:
$('.goog-te-combo').trigger('click')
$('.goog-te-combo').change()
UPDATE: FYI this is not my site. I was using the Chrome console to load jQuery and execute the jQuery methods.
I know this is already an old topic, but I just wanna share the solution I came up with the issue on firing the google translate select element change event.
Add function that will use the dispatchEvent or fireEvent function:
function triggerHtmlEvent(element, eventName) {
var event;
if(document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, true);
element.dispatchEvent(event);
} else {
event = document.createEventObject();
event.eventType = eventName;
element.fireEvent('on' + event.eventType, event);
} }
after setting the value, get the DOM object for select (using document.getElement...) and call the function above:
triggerHtmlEvent(selectObject, 'change');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With