Dynamically modifying an SVG filter with javascript
It would be simpler to do this using ordinary DOM rather than jquery. Move the id to the feGaussianBlur element
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<filter>
<feGaussianBlur id="blur" stdDeviation="0" />
</filter>
</svg>
And then
document.getElementById("blur").setAttribute("stdDeviation", "5");
or alternatively
document.getElementById("blur").setStdDeviation(5, 5);
This question is old, but it's worth answering.
There are two reasons why setting/getting attributes with jQuery on SVG elements might not work:
1. Letter case
jQuery has this code in its attr()
implementation:
if ( .... || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
In other words, it reads/sets the attribute stddeviation
, not
stdDeviation
.
2. Attributes vs properties
In old jQuery versions, the propetry, instead of the attribute, is used. This casuses things to fail if the property is not a simple string value (E.g., "For an SVG element, className is not a string, but an instance of SVGAnimatedString". E.g., There isn't really a stdDeviation property at all, but X and Y ones). See the documentation of prop()
and attr()
for more information.
So, what to do?
Here's an implementation of xattr()
, which works where attr()
fails, because it doesn't try to be smart. Use it instead of attr()
.
jQuery.fn.xattr = function(name, val) {
if (val !== undefined) {
this.each(function() {
this.setAttribute(name, val);
});
return this;
}
else {
if (this.length)
return this[0].getAttribute(name);
}
};