javascriptjquerygoogle-translate

Detect Google Website Translator change of language


I'm using the Google Website Translator on my website to let the user translate the site on the fly. Using this code:

    function googleTranslateElementInit() {
        new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar,de,el,en,es,fr,it,ja,ko,nl,ru,zh-CN', layout: google.translate.TranslateElement.FloatPosition.BOTTOM_RIGHT}, 'google_translate_element');
    }

This works great, only thing now is that I need to know which language the user has actually selected. I want to detect both when the user manually selects a language and also when the translator makes an automated translation, as its enabled to do automatic translations based on the browser settings.

What I want to do is to add an event listener to when the language is changed. I.e. not only when the user manually sets the language but every time the translator actually does a translation. E.g. when the translation starts or finishes or when the page "refreshes" to show the new language.

I need to collect this information and send it to the server to know what language to use for e-mails that are sent to the user at a later stage. As this information is gathered from multiple places, I don't want to manually check the selected language every time I required the information, but to add an event listener that detects the language changing and triggers an AJAX method to save the information in session on the server.

Thanks!


Solution

  • When the user manually selects a language (changes the value of the selectbox) you might get the language chosen with

    $('.goog-te-combo').on('change',function(){
           language = $("select.goog-te-combo option:selected").text();
            alert(language);
        });
    

    Fiddle

    In case when your page refreshes and the translator translates your page, you could get the current language that is being used by using a setTimeout. This isn't perfect, but it certainly helps mate.. :)