Search code examples
google-apigoogle-translatetranslategoogle-translation-api

Google translate API is also translating notranslate class


i have following code here

<body>
    <p id="textField">You can translate the <span class="notranslate"  translate="no" >content of this page</span> by selecting a language in the select box.</p>
    <h1 id="title">My Web Page</h1>
    <p>Hello everybody!</p>
    <p>Translate this page:</p>
    <form>
        <select id="targetLanguage">
            <option value="en">English</option>
            <option value="hi">Hindi</option>
        </select>

        <input type="button" id="translateButton" value="Translate" />
    </form>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("#translateButton").click(function () {

            var url = "https://translation.googleapis.com/language/translate/v2";
            //Strings requiring translation
            url += "?q=" + $("#textField").text();
            url += "&q=" + $("#title").text();
            //Target language
            url += "&target=" + $("#targetLanguage").val();
            //Replace with your API key
            url += "&key=API_KEY_if You need to test i can share";
            $.get(url, function (data, status) {
                //Results are returned in an array following the order they were passed. 
                $("#textField").text(data.data.translations[0].translatedText);
                $("#title").text(data.data.translations[1].translatedText);
            });       
        });
    </script>  
</body>

What i want is simply ignore the contents of no translate class and dont touch or go inside those classes, but google does not listen.

is thers any way i can fix this issue??


Solution

  • Your sending to Google api your nodes text content instead of sending HTML.

    Replace your code (line 20-22) by:

    //Strings requiring translation
    url += "?q=" + encodeURIComponent($("#textField").html());
    url += "&q=" + encodeURIComponent($("#title").html());
    

    The .text() jQuery method will only retrieve the text content of the targeted elements, removing all html. But you want to send HTML, as you need Google to retrieve the translate="no" attribute in order to avoid translating this part of the text.

    Also, I would recommend to use the encodeURIComponent function to encode the html you will send through query string. It will prevent unexpected behaviors in case your html contains special characters like &

    You will also have to use html() method instead of text to replace back your content.

    $("#textField").html(data.data.translations[0].translatedText);
    $("#title").html(data.data.translations[1].translatedText);