Aaron Aaron - 5 months ago 23
CSS Question

SVG filter not working when imbedded with JavaScript

I have been trying to get the blur effect to work when creating the elements and imbedding them with JavaScript. I cannot figure out why the blur will not show up. I have two fiddles, one with the standard HTML & CSS and the other using JavaScript. If anyone wants to check them out and offer an explanation as to what I am doing wrong I would really appreciate it.

HTML & CSS Version (Works)
https://jsfiddle.net/aaronbalthaser/xampLtnr/

HTML:

<div id="container">
<img src="http://lorempixel.com/300/250/sports/" width="300" height="250" />
<svg width="300" height="60" viewbox="0 0 300 60">
<defs>
<filter id="blur">
<fegaussianblur in="SourceGraphic" stddeviation="5" />
</filter>
</defs>
<image filter="url(#blur)" xlink:href="http://lorempixel.com/300/250/sports/" x="0" y="-190" height="250px" width="300px" />
</svg>
</div>


CSS:

#container {
position: relative;
width: 300px;
height: 250px;
margin: 0 auto;
position: relative;
}

svg {
position: absolute;
bottom: 0;
left: 0;
}


JavaScript Version (Doesn't Work)
https://jsfiddle.net/aaronbalthaser/Lbnkfn02/

HTML:

<div id="container">
<img src="http://lorempixel.com/300/250/sports/" width="300" height="250" />


</div>


CSS:

#container {
position: relative;
width: 300px;
height: 250px;
margin: 0 auto;
position: relative;
}

svg {
position: absolute;
bottom: 0;
left: 0;
}


JS:

var width = 300;
var height = 250;
var viewbox = "0 0 300 60";
var namespace = 'http://www.w3.org/2000/svg'
var path = 'http://lorempixel.com/300/250/sports/';
var container = document.getElementById('container');
var body = document.body;

var svg = document.createElementNS(namespace,'svg');
svg.setAttribute('width', width);
svg.setAttribute('height', 60);
svg.setAttribute('viewBox', viewbox);

var defs = document.createElementNS(namespace, 'defs');
var filter = document.createElementNS(namespace, 'filter');
filter.setAttribute('id', 'blur');

var feGaussianBlur = document.createElementNS(namespace, 'feGaussianBlur');
feGaussianBlur.setAttribute('in', 'SourceGraphic');
feGaussianBlur.setAttribute('stdDeviation', '5');

var image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
image.setAttribute('filter', 'url(#blur)');
image.setAttribute('xlink:href', path);
image.setAttribute('x', + '0');
image.setAttribute('y', + '-190');
image.setAttribute('height', height + 'px');
image.setAttribute('width', width + 'px');

filter.appendChild(feGaussianBlur);
defs.appendChild(filter);
svg.appendChild(defs);
svg.appendChild(image);
container.appendChild(svg);

console.log(container);

Answer
image.setAttribute('xlink:href', path);

should be

image.setAttributeNS("http://www.w3.org/1999/xlink", 'xlink:href', path);

https://jsfiddle.net/Lbnkfn02/2/

Comments