javascript – Bilingual website with JS

Question:

I needed to put up a bilingual site and found this script below, which by the way helped a lot, but it always shows the two "BR" "ENG" versions before "hiding" one of them. Even changing the order of events it continues to show both languages. I'm missing something, but I'm not realizing it. Does anyone have a light?

This is the code:

<script type="text/javascript">
        function createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else
                expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        }
        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ')
                    c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) === 0)
                    return c.substring(nameEQ.length, c.length);
            }
            return null;
        }
        function language(lang_on, lang_off) {
            createCookie("langue_on", lang_on, 365);
            createCookie("langue_off", lang_off, 365);
            for (var i = 0; i < document.getElementsByTagName("div").length; i++) {
                if (document.getElementsByTagName("div")[i].lang === lang_on) {
                    document.getElementsByTagName("div")[i].style.display = "block";
                }
                if (document.getElementsByTagName("div")[i].lang === lang_off) {
                    document.getElementsByTagName("div")[i].style.display = "none";
                }
            }
        }
        function startlanguage() {
            var notdefined;
            var lang_on = readCookie("langue_on");
            var lang_off = readCookie("langue_off");
            if (lang_on === notdefined) {
                lang_on = "pt";
            }
            if (lang_off === notdefined) {
                lang_off = "en";
            }
            language(lang_on, lang_off);
        }
        window.onload = function () {
            startlanguage();
        };
    </script>

I call the function this:

<div lang="en">ENGLISH!</div>
<div lang="pt">PORTUGA!</div>

Answer:

I created a function for you that is: http://jsfiddle.net/3ywm7Lyq/

Instead of using a cookie I used localStorage, you can change the default language value in line 2 of the javascript code….

Scroll to Top