Google Translate Widget - Translation complete callback

RichardAtHome picture RichardAtHome · Oct 15, 2012 · Viewed 8.5k times · Source

I'm using the google translate widget on one of my sites with the following google supplied code:

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

<script>

My problem: The translate runs after the page has loaded but I also have a script that auto sizes my primary navigation elements based on their width.

This runs before the translate has finished so it resizes based on untranslated English labels. Once the translate has changed the navigation wording, the navigation elements need to be resized to fit the newly translated words as they are likely to be different size (width) to the English.

I've tried calling the Google translate code before I run the code to resize the primary navigation but the translate runs asynchronously so my code runs before the translate is complete.

Is there a callback event raised when the translation is complete (or some way to detect when the translation is complete), so I can wait before I attempt to resize the navigation?

Also, I need to run a script AFTER the page has finished translating.

Answer

RichardAtHome picture RichardAtHome · Oct 15, 2012

Here's the fix I ended up using:

jQuery(function(){
    firstMenu = $("#nav li:first").text();

    setTimeout(waitNav, 500);
});

function waitNav() {

    if (firstMenu != $('#nav li:first').text()) {

        initNav();
        firstMenu = $('#nav li:first').text();
        setTimeout(waitNav, 500);

    }
    else {
        setTimeout(waitNav, 500);
    }

}

Basically, keep checking if a known piece of text has changed (in this case it's the first item in the navigation block).

If it's changed that means the translator has run, run the code you need to run after the translation (initNav() here).

I keep checking for changes in case the user selects another language.

It's not perfect, but it works for me :-)