jquerybrowsermultilingualnavigator

Display divs based on browser language with show/hide function (error: nothing shows up)


I want to display a paragraph on a website in different languages, depending on the browsers settings (unfortunately it has to be done using jQuery).

So far I have gotten as far as that I can display the language of the browser back to me but when I try to show/hide the div element based on the language it just shows neither.

I have already tried putting "===" instead of "==" and the language code seems to be correct (I tested it with an alert).

What have I done wrong? Heres my fiddle http://jsfiddle.net/o4um72af/4/

var userLang = navigator.language || navigator.userLanguage;

    if (userLang == "en-GB") {
         $("#english").show();
    }
    else {
         $("#english").hide();
    }
            
    if (userLang == "de") {
         $("#deutsch").show();
    }
    else {
         $("#deutsch").hide();
    }

Solution

  • Your code to detect language works correctly. To me, it's displaying the English version as I have en-GB language set. However, what you are doing (at least based on the provided jsFiddle) is hiding both available divs - hiding the #english div if the language is not en-GB and hiding the #deutsch div if the language is not de. So if a user has a different browser language setting (eg. fr or en-US) both divs will be hidden.

    Furthermore, you are already hiding the divs via CSS, so there is no need to do the hiding in else parts of the statement.

    I would recommend changing code to something like this

    var userLang = navigator.language || navigator.userLanguage;
    
    if (userLang == "de") {
         $("#deutsch").show();
    } else {
         $("#english").show();
    }
    

    That way, you will display the Deutsch div for people with de language setting and English div for everyone else (which is what I imagine you want?)

    If the code you have somewhere else does not appear to show any div, like you suggest, then you probably have some other CSS rules or JS hiding both divs which you forgot to include in the fiddle.

    Btw, the only difference between the == and === comparison is checking whether the type of both sides of the argument also matches, not just the value. So 5 == '5' would be true (notice, you are comparing an integer with value 5 to a string with value 5) whereas 5 === '5' would not be true - ie. the ===, also known as the strict equality is stricter than the == equality operator :) The strict equality sign is often used when guarding against potential mistakes such as adding a number and a string together (eg. 5 + 3 = 8 - notice both are integers and the result is an integer, but '5' + 3 = '53' - notice, one is a a string and the other is an integer, the result is a string)