8

I'm playing around with applying SVG filters to HTML. This works if everything's hard coded, although I need the -webkit-filter CSS id for chrome. When attempting to create an SVG element with a filter dynamically with javascript it fails. Can anyone explain why?

Here's what I have so far: http://jsfiddle.net/H3UX8/1/

The first image and text pair are blurred on chrome and firefox but the second pair are not.

The extract doesn't work:

.dynamic div {
    -webkit-filter: url('#f2');
    filter: url('#f2');
}

...

var svg = document.createElement("svg");
var filter = document.createElement("filter");
filter.setAttribute("id", "f2");
var blur = document.createElementNS("http://www.w3.org/2000/svg", "feGaussianBlur");
blur.setAttribute("stdDeviation", "5");
filter.appendChild(blur);
svg.appendChild(filter);
document.body.appendChild(svg);

...

<div class="dynamic">
    <div><img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" /></div>
    <div>HELLO WORLD TWO</div>
</div>

The html syntax looks identical. I'm guessing either document.createElement doesn't create svg capable tags or maybe the filter IDs are only read once on document load. I can, however, dynamically change the value of stdDeviation in the static example.

1 Answer 1

13

Try this:

var NS = "http://www.w3.org/2000/svg";
var svg = document.createElementNS( NS, "svg" );

var filter = document.createElementNS( NS, "filter" );
filter.setAttribute( "id", "f2" );

var blur = document.createElementNS( NS, "feGaussianBlur" );
blur.setAttribute( "stdDeviation", "5" );

filter.appendChild( blur );
svg.appendChild( filter );
document.body.appendChild( svg );
2
  • Works straight away, thanks! Can you explain or post a link explaining why I need the namespace URI version of the call?
    – jozxyqk
    Commented Dec 2, 2013 at 8:00
  • 4
    If you don't put the SVG elements in the SVG namespace then they end up in the default (HTML) namespace and are not recognised by the SVG parser. Commented Dec 2, 2013 at 8:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.