Jquery – Trigger Google Web Translate Element

google-translatejquery

Since the google translation api is shutting down, I am trying to get the google translate web element to work across the entire session for a user, so that they do not have to change the select box option to their language on each different page.

The initial load function is given as follows:

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

Where google_translate_element is the div into which to put the select box. When the select box is in there it always has the class "goog-te-combo". I can change the value of the box using jQuery with no issue, eg. $('.goog-te-combo').val('fr') will change the box to French.
But when I try to trigger the translation using $('.goog-te-combo').trigger() using all sorts event types (change, click, mouseup, mousedown, etc) the translation never fires.

Does anyone know of a way to trigger the translation?

Best Answer

This is an old question but I'll answer since i had the same problem and got around it. I had to get the DOM from jQuery and fire and execute.

 function fireEvent(element,event){
     console.log("in Fire Event");
    if (document.createEventObject){
            // dispatch for IE
            console.log("in IE FireEvent");
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
            // dispatch for firefox + others
            console.log("In HTML5 dispatchEvent");
            var evt = document.createEvent("HTMLEvents");
            evt.initEvent(event, true, true ); // event type,bubbling,cancelable
            return !element.dispatchEvent(evt);
    }
 }

And I call it using

 var jObj = $('.goog-te-combo');
 var db = jObj.get(0);
 jObj.val(Lang);
 fireEvent(db, 'change');