Google translate get current language

Naterade picture Naterade · Nov 20, 2012 · Viewed 13.7k times · Source

After finding zero of anything to help me online....

I am using the current function for a multi language site:

function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'en,es',     layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}

However I have no idea how to get the current language once a user changes it. I'm not sure if this is even possible. Basically I want to update to Spanish images if Spanish is chosen over English. Any help would be appreciated!

Answer

jchip picture jchip · Dec 15, 2014

The currently selected language is stored in a cookie named googtrans.

Here's a simple example of grabbing the value from the cookie (based on cookie code from here: What is the shortest function for reading a cookie by name in JavaScript?):

function readCookie(name) {
    var c = document.cookie.split('; '),
    cookies = {}, i, C;

    for (i = c.length - 1; i >= 0; i--) {
        C = c[i].split('=');
        cookies[C[0]] = C[1];
     }

     return cookies[name];
}
console.log(readCookie('googtrans')); //eg. 'en/no' for Norwegian, '/en/hr' for Croatian, etc.