Swap styles with multiple name with JS
I had a problem where I wanted to swap the background color of a given div dynamically between two colors (alternating rows in a list) depending on which item was selected. Originally, I was just doing this:
for(i=1;i<=intNumOfLines;i++){
// turn them all off
document.getElementById(column+i).style.backgroundColor = ‘#CCC’;
}
// turn selected one on
document.getElementById(column+x).style.backgroundColor = ‘#FFF’;
This did what I wanted, but wasn’t very CSS oriented cuz the colors would be set in the javascript. So then I decided to store it at the class level in CSS and just swap the className as needed like this:
<div class=”lineOn”>Line 1</div>
<div class=”lineOff”>Line 1</div>
CSS:
.lineOn, .lineOff{lots of styles…;background-color:#FFF;}
.lineOff{background-color:#CCC;}
JS:
for(i=1;i<=intNumOfLines;i++){
// turn them all off
document.getElementById(column+i).className = ‘lineOff’;
}
// turn selected one on
document.getElementById(column+x).className = ‘lineOn’;
Now I was happy…. for a while. Then I didn’t like that the colors were stuck in the .lineOn and .lineOff. I wanted to create global color schemes in my CSS files, so I then moved the colors to their own class and then reff’d two separate classes like so:
<div class=”line colorOn”>Line 1</div>
<div class=”line colorOff”>Line 1</div>
CSS:
.colorOn{background-color:#FFF;}
.colorOff{background-color:#CCC;}
.line{lots of styles…;}
Now I was happy with my CSS design. The problem I ran into was that my javascript to change the className didn’t work when I wanted to swap .colorOn for .colorOff, so it was on to Google to figure something out.
With the help from this article on eVolt.org, I got this code:
function modCSS(a,o,c1,c2){
// a = action (swap, add, remove, check)
// o = object
// c1 = class1
// c2 = class2
switch (a){
case ’swap’:
o.className=!modCSS(’check’,o,c1)?o.className.replace(c2,c1): o.className.replace(c1,c2);
break;
case ‘add’:
if(!modCSS(’check’,o,c1)){o.className+=o.className?’ ‘+c1:c1;}
break;
case ‘remove’:
var rep=o.className.match(’ ‘+c1)?’ ‘+c1:c1;
o.className=o.className.replace(rep,”);
break;
case ‘check’:
return new RegExp(’\\b’+c1+’\\b’).test(o.className)
break;
}
}
// call the function
for(i=1;i<=intNumOfLines;i++){
modCSS(’remove’,document.getElementById(column+i),’colorOn’);
modCSS(’add’,document.getElementById(column+i),’colorOff’);
}
// Turn on the requested one
modCSS(’swap’,document.getElementById(column+i),’colorOff’,'colorOn’);
volia! It worked. Yay =)
! most of this code was written on-the-fly for this post, so there may be type-o’s. This was to give you the idea and methodology that I used to solve my problem
Discussion Area - Leave a Comment