Mutant Bob
Mutant Bob

Reputation: 3549

How do I assign an external CSS file to a javascript-constructed SVG object?

I am using javascript to construct an SVG graphic which I then insert into the web page. I would like to assign a style sheet (from an external .css file) to this dynamically created SVG, but the examples I've seen of SVGs with style sheets have the style references outside the SVG element.

Here's my javascript that constructs the SVG object:

LVMGrapher.prototype.getCanvas = function()
{
    if (this.canvas==null) {
    var wrap = document.getElementById("svgWrap");
    this.canvas = document.createElementNS(SVG_NS, "svg");
    removeAllChildren(wrap);
    wrap.appendChild(this.canvas);
    }
    return this.canvas;
}

and later

var svg = this.getCanvas();
var svgNS = svg.namespaceURI;

svg.setAttribute("preserveAspectRatio", "xMinYMin meet");
svg.setAttribute("viewBox", "0 0 1000 400");
svg.setAttribute("width", "100%");

I later fill the SVG with graphics and right now I hard-code the colors, but I'd rather just give them classes and let the style sheet control the color scheme. There's no good reason someone should have to dig into my javascript to be able to control the colors.

The exerimental app is at http://www.purplefrog.com/~thoth/exp/lvm-graph/

Bonus points if you reference a tutorial on how to synthesize a style sheet from javascript. But my primary use case is a style sheet from a URL.

Upvotes: 1

Views: 655

Answers (2)

Mutant Bob
Mutant Bob

Reputation: 3549

Using the brief answer from Erik Dahlström I achieved success with the following code:

function addStyle(svg)
{
    var style = document.createElement("style");
    style.appendChild(document.createTextNode("@import url('bacon2.css')"));
    svg.appendChild(style);
}

However, I think I will go with the solution Stephen Thomas led me to. The style of the enclosing document applies to SVG elements that are fabricated and inserted by javascript.

When I formulated the original question I was misdirected by the nature of SVG documents that are included by the <object> tag which (unlike in-line SVG) do not inherit the style sheet of the referring HTML document.

The synthesized <style> tag will still be useful to programmers who want to augment the style of the enclosing HTML document.

Upvotes: 0

Erik Dahlstr&#246;m
Erik Dahlstr&#246;m

Reputation: 60976

Some ways of doing this:

  • insert a style element that has an @import statement that references the external stylesheet
  • insert a link element (note: must be created in the XHTML namespace, so use createElementNS) that references the external stylesheet
  • create an xml-stylesheet processing instruction that references the external stylesheet
  • insert a style element and with the text content being the text content of an XMLHttpRequest that you made to fetch the external stylesheet

I would recommend either of the first two options.

Upvotes: 1

Related Questions