Forum Moderators: not2easy

Message Too Old, No Replies

How Can I Detect Whether A Style Exists in JavaScript?

I need to see if the webmaster has provided a style

         

cmarshall

7:57 pm on Aug 18, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Here's the scenario:

I am writing some reusable code that is saturated by CSS. One of the elements has an "optional" rollover. This means that if the Webmaster has provided a particular style in their stylesheet, I can do a rollover effect. If not, I just ignore it.

I need to use Javascript because I want to change the class of an enclosing <div>, allowing the designer to change all of the enclosed items at once, based upon the change in parent class.

In particular:


<table id="march_31" class="unselected_day">
<tr class="daynum"><td><a href="javascript:goto_day(3,31,2005)" onmouseover="(HERE IS MY QUESTION)" onmouseout="(HERE IS MY QUESTION)">31</a></td></tr>
<tr class="day_contents"><td>OTHER STUFF</td></tr>
</table>

What I want to do, is see if the designer has provided a "daynum_rollover" class. If so, I would change the wrapper to have this class, like so:


document.getElementById('march_31').style = "daynum_rollover";

This would allow the designer to provide alternate encapsulated styles that only take effect when the "daynum_rollover" class is assigned to the container. For example:


.unselected_day .daynum, .unselected_day .day_contents {
background-color: #fff;
}
.daynum_rollover .daynum, .daynum_rollover .day_contents {
background-color: #000;
color: #fff;
}

If I could embed the following pseudocode into the onMouseOver() function, this would do it:


if ( the style "daynum_rollover" exists ) then document.getElementById('march_31').style = "daynum_rollover";
else do nothing;

Any ideas? I can't seem to find the answer anywhere.

This would be the dynamic detection of an existing style (not stylesheet, and not the class of an element).

garann

10:19 pm on Aug 18, 2005 (gmt 0)

10+ Year Member



What if, instead of checking whether they've added the class, your basic implementation simply defined the
unselected_day
and
daynum_rollover
the same way? If they wanted a change on mouse over, they could change the CSS for
daynum_rollover
. Otherwise, the JS would fire, but nothing would appear to happen.

Incidentally, you'd want to use className here:


document.getElementById('march_31').[b]className[/b] = "daynum_rollover";

cmarshall

10:51 pm on Aug 18, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yeah, that's what I'm going to do. I'll leave the surrounding element blank, and add the rollover class.

I just hate leaving a challenge.

This is one of those things where you just figure "of course it's done all the time," but then you figure out that, no, not really...