Log in

View Full Version : Chaining CSS class with Javascript in IE problems



zkac054
10-01-2006, 01:08 PM
Hi all,

I've recently found out that you can change an element's class using Javascript and thought I'd try it out. Here's the Javascript code I used which is called on an onMouseOver event:



var testArray=Array(), d=document;

function init(){
index=0;
num=d.getElementsByTagName("span");

for(i=0;i<num.length;i++){
if(num[i].id=("test")){
testArray[index]=num[i];
index++;
}
}
}

// onMouseOver
function show(i){
for(x=0; x<testArray.length; x++){
if(x == i){
testArray[x].className="normal";
}
else{
testArray[x].className="hideMe";
}
}
}


which is all well and works a treat with FireFox, but when I tried it out in IE (ver6) it didnt work. I've spent ages trying to figure out why, but I dont know why it doesnt work with IE. Does anyone have any ideas?

Twey
10-01-2006, 02:00 PM
You're using a lot of undefined variables and some odd logic there. I'm surprised it works in FX.
if(num[i].id=("test")){className, not id: only one element can have a given ID. Also, note that this is an assignment, which would have had the effect of setting the class of every span on the page to "test" and then adding them to the array.
var testArray = [];

function init() {
for(var i = 0, els = document.getElementsByTagName("span"); i < els.length; ++i)
if(els[i].className === "test")
testArray.push(els[i]);
}

function show(n) {
for(var i = 0; i < testArray.length; ++i)
testArray[i].className = "hideMe";
testArray[n].className = "normal";
}

zkac054
10-02-2006, 12:56 PM
thanks for the reply. I was under the impression that you can get away with having undefined variables in javascript. I havent played around with javascript for ages!

Anyway what I was doing was trying to recreate something I saw on here: http://www.virginradio.co.uk/ when a user hovers over a link the news item appears, whereas all the other news items remain hidden. I thought I could use ids to recreate this effect

Twey
10-02-2006, 04:59 PM
I was under the impression that you can get away with having undefined variables in javascript.You can. It's just not a good idea. :)

Undefined variables automatically become global, meaning that memory is used much less efficiently than needs to be the case.
I thought I could use ids to recreate this effectYou can, but not that way.

zkac054
10-03-2006, 12:17 AM
ha ha thanks. Well, I'll have another bash at it. Any pointers would be appreciated though :D

Twey
10-03-2006, 06:15 AM
You should use classes, as I showed above.