473,403 Members | 2,354 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

Dynamic CSS-creation (Firefox)

Hi,
can anybody tell me how you can create a new stylesheet inside a
(X)HTML page with JavaScript and Firefox, if the stylesheet is only
available as a variable value, like:

var CSSStyle = "rect {fill: lightgrey;}
circle {fill: red;}
polyline {fill: none; stroke: red; stroke-width: 0.3;}
text {font-size: 2.5px;}
text.text-x-axis {text-anchor: middle;}
text.text-y-axis {text-anchor: end;}"

So far, the only workaround I found, was to link an empty stylesheet to
the page

<link rel="stylesheet" type="text/css" href="./empty.css"/>

and then use the insertRule method on this stylesheet for every single
rule from the variable (indexOf('}') / substring()).

Thanx
Stefan

Jun 2 '06 #1
3 6402


Capricorn wrote:

can anybody tell me how you can create a new stylesheet inside a
(X)HTML page with JavaScript and Firefox, if the stylesheet is only
available as a variable value, like:

var CSSStyle = "rect {fill: lightgrey;}
circle {fill: red;}
polyline {fill: none; stroke: red; stroke-width: 0.3;}
text {font-size: 2.5px;}
text.text-x-axis {text-anchor: middle;}
text.text-y-axis {text-anchor: end;}"


If you have an XHTML page (served as application/xhtml+xml or
application/xml or text/xml) then you can do e.g.

var styleElement =
document.createElementNS('http://www.w3.org/1999/xhtml', 'style');
styleElement.type = 'text/css';
styleElement.appendChild(document.createTextNode(C SSStyle));
var head =
document.documentElement.getElementsByTagNameNS('h ttp://www.w3.org/1999/xhtml',
'head')[0];
if (head != null) {
head.appendChild(styleElement);
}

That works fine here for me with Firefox 1.5 and with some Opera 9 beta
weekly.
--

Martin Honnen
http://JavaScript.FAQTs.com/
Jun 2 '06 #2
That works fine here too. Thanx.

Stefan

"Ich sah den Wald vor lauter Bäumen nicht..."

Jun 2 '06 #3
Capricorn wrote:
Hi,
can anybody tell me how you can create a new stylesheet inside a
(X)HTML page with JavaScript and Firefox, if the stylesheet is only
available as a variable value, like:

var CSSStyle = "rect {fill: lightgrey;}
circle {fill: red;}
polyline {fill: none; stroke: red; stroke-width: 0.3;}
text {font-size: 2.5px;}
text.text-x-axis {text-anchor: middle;}
text.text-y-axis {text-anchor: end;}"

So far, the only workaround I found, was to link an empty stylesheet to
the page


Try the following class which encapsulates a CSSStyleSheet and covers major browser differences (Tested on FF, IE and Opera, YMMV). It allows you to dynamically add and change rules keyed by their selector text, and to enquire upon style attributes of rules.

To use it use:

var sheet = new CSSStyleSheet();
sheet.addRule(".myclass", "background-color:red");
/**
An object which encapsulates a dynamically created, modifiable stylesheet.
*/
function CSSStyleSheet()
{
/**
* The array of rules for this stylesheet.
* @private
*/
this.rules = [];

/**
* An associative array, keyed by the selector text containing the rule index number for
* the rule for that selector text.
* @private
*/
this.ruleIndex = [];

if (document.createStyleSheet)
{
this.sheet = document.createStyleSheet();
}
else
{
this.styleElement = document.createElement("style");
document.getElementsByTagName("head")[0].appendChild(this.styleElement);
this.sheet = this.styleElement.styleSheet ? this.styleElement.styleSheet : this.styleElement.sheet;
}
}

/**
Create a style rule in the stylesheet.
@param selectorText The CSS selector text.
@param ruleText The style specification with or without braces.
*/
CSSStyleSheet.prototype.addRule = function(selectorText, ruleText)
{
var result;

// Opera, and other browsers with no DOM stylesheet support
if (!this.sheet)
{
// Remove braces.
ruleText = ruleText.replace(/^\{?([^\}])/, "$1");

// If it exists, modify it.
if (!this.ruleIndex[selectorText])
this.ruleIndex[selectorText] = this.rules.length;
this.rules[this.ruleIndex[selectorText]] = ruleText;

// Build the innerHTML of the <style> element from our rules.
var cssText = "";
for (var sel in this.ruleIndex)
cssText = sel + " {" + this.rules[this.ruleIndex[sel]] + "}";
this.styleElement.innerHTML = cssText;
}

// IE.
// Each rule object has a style property which contains the style attributes.
else if (this.sheet.addRule)
{
// addRule() requires no braces
ruleText = ruleText.replace(/^\{?([^\}])/, "$1");
var r = this.sheet.rules.length;
this.sheet.addRule(selectorText, ruleText);
result = this.sheet.rules[r];
this.ruleIndex[selectorText] = r;

if (this.rules.length == 0)
this.rules = this.sheet.rules;
}

// DOM standard. Result object contains looks like {cssText:selectorText + " " + ruleText}
// cssText property is readonly. deleteRule(ruleIndex} must be used to remove.
else if (this.sheet.insertRule)
{
// insertRule() requires braces
if (!/^\{[^\}]*\}$/.test(ruleText))
ruleText = "{" + ruleText + "}";

var r = this.sheet.cssRules.length;
this.sheet.insertRule(selectorText + " " + ruleText, r);
result = this.sheet.cssRules[r];
this.ruleIndex[selectorText] = r;

if (this.rules.length == 0)
this.rules = this.sheet.cssRules;
}
else
{
alert("Cannot create rule");
}
return result;
}

/**
* Change a style property in a rule.
* @param selectorText The identifier of the rule to change
* @param property The name of the style property to change
* @param value The new value of the style property.
*/
CSSStyleSheet.prototype.changeRule = function(selectorText, property, value)
{
var index = this.ruleIndex[selectorText];

// If the rule is not present, create it.
if (typeof index == "undefined")
{
this.addRule(selectorText, property + ":" + value);
}

// Opera, and other browsers with no DOM stylesheet support
if (!this.sheet)
{
var cssText = this.rules[index];
if (cssText)
{
var propSearch = new RegExp("^(.*" + property + "\\s*\:\\s*)([^;]*)(.*)$");
var ruleText = propSearch.exec(cssText);
// If the value was in the old rule...
if (ruleText)
{
// And it was different...
if (ruleText[4] != value)
{
this.rules[index] = ruleText[1] + value + ruleText[3];
}
}
else
{
this.rules[index] = cssText + "; " + property + ": " + value + ";";
}

// Rebuild the innerHTML of the <style> element from our rules.
cssText = "";
for (var sel in this.ruleIndex)
cssText = sel + " {" + this.rules[this.ruleIndex[sel]] + "}";
this.styleElement.innerHTML = cssText;
}

var cssText = "";
var cssText = "";
for (var sel in this.ruleIndex)
cssText = sel + " {" + this.rules[this.ruleIndex[sel]] + "}";
}

// rules contain a style object - easy
else if (this.rules[index].style)
{
// Make the property camelCase
var m = /^([^-]*)-([a-z])(.*)$/.exec(property);
while (m)
{
property = m[1] + m[2].toUpperCase() + m[3];
m = /^([^-]*)-([a-z])(.*)$/.exec(property);
}

// Use the style property of the rule.
this.rules[index].style[property] = value;
}

// DOM standard. We must parse the rule, delete, and create a new one.
else if (this.sheet.insertRule)
{
var oldRule = this.rules[index];
if (oldRule)
{
var cssText = oldRule.cssText;
var propSearch = new RegExp("^[^\\{]*(\\{.*" + property + "\\s*\\:\\s*)([^};]*)([^}]*})");
var ruleText = propSearch.exec(cssText);

// If the value was in the old rule...
if (ruleText)
{
// And it was different...
if (ruleText[4] != value)
{
cssText = ruleText[1] + value + ruleText[3];
this.sheet.deleteRule(index);
this.sheet.insertRule(selectorText + " " + cssText, index);
}
}
else
{
var propSearch = new RegExp("\\{([^}]*)}");
ruleText = propSearch.exec(cssText);
cssText = "{ " + ruleText[1] + "; " + property + ": " + value + " }";
this.sheet.deleteRule(index);
this.sheet.insertRule(selectorText + " " + cssText, index);
}
}
}
}

CSSStyleSheet.prototype.getRuleProperty = function(selectorText, property)
{
var index = this.ruleIndex[selectorText];

// If the rule is not present, create it.
if (typeof index == "undefined")
{
return;
}

// Opera, and other browsers with no DOM stylesheet support
if (!this.sheet)
{
var cssText = this.rules[index];
if (cssText)
{
var propSearch = new RegExp("^.*" + property + "\s*\:\s*([^;]*)");
var ruleText = propSearch.exec(cssText);

// If the value was in the old rule...
if (ruleText)
{
return ruleText[1];
}
}
}

// rules contain a style object - easy...
else if (this.rules[index].style)
{
// Make the property camelCase
var m = /^([^-]*)-([a-z])(.*)$/.exec(property);
while (m)
{
property = m[1] + m[2].toUpperCase() + m[3];
m = /^([^-]*)-([a-z])(.*)$/.exec(property);
}
var style = this.rules[index].style;
return style[property];
}

// DOM: We must parse the rule cssText.
else if (this.sheet.insertRule)
{
var oldRule = this.rules[index];
if (oldRule)
{
cssText = oldRule.cssText;
var propSearch = new RegExp("^.*" + property + "\\s*\\:\\s*([^};]*)");
var ruleText = propSearch.exec(cssText);

// If the value was in the old rule...
if (ruleText)
{
return ruleText[1];
}
}
}
}
Jun 3 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Manu | last post by:
Hello, i ve again a little problem with my dynamic web site... i need to insert a dynamic link (css) into my body ! Why ? because i've a html template and i insert into the body a dynamic...
3
by: JOSEPHINE ALVAREZ | last post by:
I have this code that I want to use to do a rollover. However, because the company I am doing it for is continually changing the text, I want to be able to use dynamic text to change the text on...
5
by: Gary | last post by:
I am not sure what group to post this to but here goes. I am dynamically creating a web page using perl. I grabbed a style sheet from a free site and hacked it to look the way I wanted. I then...
3
by: Daves | last post by:
what would be the easiest way to create a dynamic css file to link to eg .... <head> <link type="text/css" rel="Stylesheet" href="lis.aspx" /> </head> .... this one quite clumsy since...
2
by: JWL | last post by:
Hi I need to create a bunch of sites with slightly dynamic CSS. Basically, all the image paths in the CSS need to be dynamic, depending on the values of certain ASP variables. I can think of...
1
by: Satish.Talyan | last post by:
hi, i want to create a dynamic tree hierarchy in javascript.there are two parts in tree, group & user.when we click on group then users come under that's tree category will be opened.problem is...
2
by: czuvich | last post by:
All, I was wondering if it was possible to change a css class on a page load (somehow). Basically, I am wanting to say this: <div id="myclass" class="a javascriptfunction"> Is this...
9
by: pbd22 | last post by:
Hi. This is just a disaster management question. I am using XMLHTTP for the dynamic loading of content in a very crucial area of my web site. Same as an IFrame, but using XMLHTTP and a DIV. I...
3
by: =?Utf-8?B?U3ViYQ==?= | last post by:
I am using a asp page to dynamically create a stylesheet my asp page creates the following css element when i call the asp page my typing the url in the browser. My asp page works...
2
Frinavale
by: Frinavale | last post by:
I've created a ASP.NET control that displays a "book" of schedules. It dynamically displays scheduling times and allows the user to page through the schedules. It also lets the user edit the...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.