View Full Version : insertRule from select

04-30-2004, 10:48 AM
My script adds rules to Css but I don't know how to make it use the value of the select box which triggers the event?

Any help appreciated

<script type="text/javascript">
function addCSSRule (selectorText, declarations) {
var styleSheet;
if (document.styleSheets) {
if (document.styleSheets.length === 0) {
var styleElement;
if (document.createElement && (styleElement =
document.createElement('style'))) {
styleElement.type = 'text/css';
styleSheet = styleElement.sheet;
if (document.styleSheets.length > 0) {
styleSheet = document.styleSheets[document.styleSheets.length - 1];
if (styleSheet.insertRule) {
selectorText + ' { ' + declarations + ' }',
else if (styleSheet.addRule) {
styleSheet.addRule(selectorText, declarations);

font Size<select name="size" onclick="addCSSRule('div', 'font-size: (this:value);');">
<option value="12px" SELECTED>12px</option>
<option value="15px">15px</option>
<option value="20px">20px</option>
<option value="25px">25px</option>

<div>this div</div>

Willy Duitt
04-30-2004, 11:15 AM
<select name="size" onclick="addCSSRule('div', 'font-size:'+this.value)">


04-30-2004, 11:52 AM
<select name="size" onchange="addCSSRule('div', 'font-size:'+this.options[this.selectedIndex].value)">

Willy Duitt
04-30-2004, 11:56 AM

I didn't realize this.value was not cross-browser. :eek:


05-01-2004, 01:11 AM
Thanks guys that did the trick :thumbsup:

05-01-2004, 03:50 AM
I didn't realize this.value was not cross-browser.It is, however, not quite so in the case of <select> elements. Older browsers (e.g., Netscape 4.x) will not obtain the value correctly unless you use the notation Glenn has demonstrated. Glenn also pointed out that the event you want to be listening for is the onchange event, as opposed to onclick.

05-01-2004, 05:48 AM
@Willy Duitt
Lol, I figured out that myself when attempting to use it on that javascript you were helping me with. If you read this, go find my post again, I need more help :D

05-01-2004, 10:22 AM
And thanks again :D
I was wondering why my text box using onblur wasn't working guess I should have noticed the this.selectedIndex :rolleyes:

05-02-2004, 07:13 AM
Another IE handicap
With firefox I can add multiple Css selectors
onchange="addCSSRule('body, td', 'font-size:'+this.options[this.selectedIndex].value)"

but if you use more than 1 with IE it won't execute the script

Now I have a sig