Google Translate Widget - Translation complete callback

不问归期 提交于 2019-12-01 16:10:42

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 :-)

$( document ).ready(function() {
    $('#google_translate_element').bind('DOMSubtreeModified', function() {
        var val = $(this);
        var strlang = "" + val[0].innerText + "";
        console.log(strlang); // print your selected language in console
    });
});

You can detect changes like this:

$('#some-translatable-element').bind('DOMSubtreeModified', function() {
  yourCallback();
});

The drawback is that the event is beeing fired multiple times since google translate does multiple changes in the process.

A suggestion is to detect changes on the last element on your page, cause then you know all elements above is translated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!