Tuesday, November 07, 2006

Script Script Script




This blog is also about geekitude isn't it ? I said it myself. So as I worked my eyeballs out to program something which could fit in the blog to add an auto translation method, and it gave me a serious headache. I want to thanks all these fellow geeks blogging and discussing theirs issues over the net, I learnt a lot from you guys and I still am.
I would also like to give my little contribution to the big scripting family by publishing the code I made.

Basically the code is made to modify the propriety of an element's css style, and I use it to hide the layer containing the alternate content, but there are other uses.
I began with this :


cnt = "1";
lg1 = "en";
lg2 = "fr";


function translate(id)
{
if (cnt == "1")
{
lg1 = "en"+id;
lg2 = "fr"+id;
cnt = "2";
}
else
{
lg1 = "fr"+id;
lg2 = "en"+id;
cnt = "1";
}
el = document.getElementById(lg1);
attrib = "display:none;"
el.setAttribute("style", attrib);
el = document.getElementById(lg2);
attrib = "display:inline;"
el.setAttribute("style", attrib);
}

As you still don't have any getElementByClassName() function in the current version of javascript, I was oblige to increment the ID's manually, in the html as well as in the script, via the argument.
It suited me so far, I wanted to add a post by post translation, so I was happy with it.
But, but, BUT.... ie does NOT recognise the STYLE css element as a proper argument to the setAttribute function (by the way be carefull with it, it erases all the attribute you haven't set in the function)and in this case you have to use, for exemple :


myElement.style.setAttribute('cssText', myAttribute);


Then here is the final code :



cnt = "1";
lg1 = "en";
lg2 = "fr";


function translate(id)
{
if (cnt == "1")
{
lg1 = "en"+id;
lg2 = "fr"+id;
cnt = "2";
}
else
{
lg1 = "fr"+id;
lg2 = "en"+id;
cnt = "1";
}

if (document.all)
{
el = document.getElementById(lg1);
attrib = "display:none;"
el.style.setAttribute('cssText', attrib);
el = document.getElementById(lg2);
attrib = "display:inline;"
el.style.setAttribute('cssText', attrib);
}
else
{
el = document.getElementById(lg1);
attrib = "display:none;"
el.setAttribute("style", attrib);
el = document.getElementById(lg2);
attrib = "display:inline;"
el.setAttribute("style", attrib);
}
}

The if (document.all) {} is used to check if the browser is IE.
The code as it is now is heavy, I could have just defined the setAttribule in a if() and affect it to a variable, but well, it works well now, so let us all enjoy !





No comments: