fbpx

Uncaught TypeError: Cannot read property ‘InlineLayout’ of undefined

This error, or any error mentioning cannot read property, typically gets thrown when you try to run a function or reference a property on an object that doesn’t exist. For example, I was using the Google Translate widget and ran the JavaScript code below:

new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'es,en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false}, 'dgt_google_translate_element');

The following error: Uncaught TypeError: Cannot read property ‘InlineLayout’ of undefined means that google.translate.TranslateElement doesn’t exist, so when I try to access the InlineLayout property on that object there is nothing there.

So, I need to ensure that the google.translate.TranslateElement exists prior to running the above function.

I solved this by ensuring that the script that held the google object was loaded before I ran the function above. In order to do this, I used the setInterval JS function. If the script exists, I run clearInterval to prevent the checkScriptExists function from running infinitely.

var timer = setInterval(checkScriptExists, 3000);
function checkScriptExists(){
     var google_script_url = "//translate.google.com/translate_a/element.js";	 
     if($("script[src*='"+google_script_url+"']")[0]){
        // run google translate function
        new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'es,en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false}, 'dgt_google_translate_element');
        clearInterval(timer);
        return;
    } 
}

Leave a Reply

Your email address will not be published. Required fields are marked *