Access a CSS class through Javascript
I have a panel (asp.net) with a CSS class that sets the background color. When I click the panel I want to alternate the background color back and forth between two values.
Then initial bg color in the css:
Code:
.panelOpenStyle
{
background-color: #808080;
}
The only way I can seem to do it is to hard-code the color values in javascript:
Code:
if(document.getElementById('panel1').style.backgroundColor == '#808080')
document.getElementById('panel1').style.backgroundColor = '#6699CC';
else
document.getElementById('panel1').style.backgroundColor = '#808080';
I would like to use these two CSS classes so I wouldn't have to hard code the values in Javascript:
Code:
.panelOpenStyle
{
background-color: #808080;
}
.panelCloseStyle
{
background-color: #6699cc;
}
Is there some way for me to alternate between two CSS classes in javascript?
Re: Access a CSS class through Javascript
There you go.
Code:
function add_class(o, cls) {
var regex = new RegExp("\\b"+cls+"\\b");
if(!regex.test(o.className)) {
o.className += " " + cls;
}
}
function remove_class(o, cls) {
var regex = new RegExp("\\b"+cls+"\\b");
o.className = o.className.replace(regex, "");
}
function replace_class(o, ocls, ncls) {
var regex = new RegExp("\\b"+ocls+"\\b");
o.className = o.className.replace(regex, ncls);
}
Re: Access a CSS class through Javascript
That did the trick. Thanks.
What is a RegExp and why do you use it?
Why couldn't you just do this:
Code:
function replace_class(o, ncls)
{
o.className = "ncls";
}
Re: Access a CSS class through Javascript
RegEx is the regular expression prototype, used to create regular expressions.
And I can't just do the thing you proposed because elements may have more than one class. In that case, the class names are separated by spaces. The thing about my functions is that they still work correctly in that case.
For example, here's something that could easily appear in a page I'm doing:
Code:
<div class="controlgroup calendar optional">
<!-- ... -->
</div>
Now, if I wanted to add the class "invalid" to it, by using your method, the class attribute would look like:
class="invalid"
Oops. Since my entire layout depends on the "controlgroup" class, this just totally broke the page.
With my method, the class attribute looks like this:
class="controlgroup calendar optional invalid"
and I can safely remove that class again, too.
Re: Access a CSS class through Javascript
OK. Didn't know you could have more than one class associated. What if two different classes try to set the same feature? What takes precedence?
Re: Access a CSS class through Javascript
Whichever specifier is more specific. The CSS spec defines the rules. If the specifity is the same, the latter one takes precedence.