3
I had to put a bilingual site and found this script below, which by the way helped a lot, but it always shows the two versions "BR" "ENG" before "hide" one of them. Even by changing the order of events he continues to show both languages. I’m missing something, but I’m not getting it. Someone has 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 it that:
<div lang="en">ENGLISH!</div>
<div lang="pt">PORTUGA!</div>
This happens because it only properly executes the code in the event
onload
. Try to remove the callstartlanguage
of the eventonload
, but it may not work due to some element that has not yet been fully loaded by the browser at the time of code execution.– Vinícius Gobbo A. de Oliveira
When removing "startlanguage" from the function, it stops hiding the secondary language.
– Bruno Martins
I see that you are using cookies, I believe that the visibility of the div with the language can be set already in the server-side. Another alternative is to leave the two with
display: none
, then make one of the two visible in theonload
– Tobias Mesquita
Does not solve, it takes the same action when removing startlanguage.
– Bruno Martins
If the script is being loaded at the end of the body it will only be executed after the body is loaded, in this case it would be interesting to leave the script in the head along with the styles. This would force the script to run before any part of the site was rendered. You can externalize script to a file and upload it to the head.
– ooredroxoo
In both cases the script loads the two languages. Bad thing’s fault.
– Bruno Martins