Google Translate script does not translate and does not generate error

Asked

Viewed 311 times

0

I am using the following script to translate a website.

    <div id="google_translate_element"></div>

    <script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>


    <select class="select-language" onchange="ChangeLang(this.value)">

        <option value="pt">Português</option>

        <option value="en">Inglês</option>

        <option value="es">Espanhol</option>

        <option value="it">Italiano</option>

        <option value="de">Alemão</option>

        <option value="fr">Francês</option>

    </select>

And

function ChangeLang(a) {
    var b, elemento = "";
    if (document.createEvent) {
        var c = document.createEvent("HTMLEvents");
        c.initEvent("click", true, true)
    }
    if (a == 'pt') {
        elemento = $(".goog-te-banner-frame:eq(0)").contents().find("button[id*='restore']")
    } else {
        switch (a) {
            case 'de':
            b = "alem";
            break;
            case 'es':
            b = "espanhol";
            break;
            case 'fr':
            b = "fran";
            break;
            case 'en':
            b = "ing";
            break;
            case 'it':
            b = "italiano";
            break
        }
        elemento = $(".goog-te-menu-frame:eq(0)").contents().find("span:contains('" + b + "')");
    }
    if (elemento.length > 0) {
        if (document.createEvent) {
            elemento[0].dispatchEvent(c)
        } else {
            elemento[0].click()
        }
    }
}
function googleTranslateElementInit() {
    new google.translate.TranslateElement({
        pageLanguage: 'pt',
        autoDisplay: false,
        includedLanguages: 'de,es,fr,en,it',
        layout: google.translate.TranslateElement.InlineLayout.SIMPLE
    },
    'google_translate_element');
}

The files are being called, no error is generated and also no translation occurs.

@Edit Testing with onclick instead of onchange works as expected.

  • Just out of curiosity why onchange the value of the function? ChangeLang('pt')

  • My error, @Maiconcarraro. Correct is Changelang(this.value)

  • Is working again?

  • It worked as expected using onclick instead of onchange.

1 answer

0


There is a simpler way to do this and with more languages

HTML:

<div id="google_translate_element">

  <script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

</div>

Javascript:

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

Example in CODEPEN

Change the value of string "pageLanguage" if necessary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.