I need to compute new and edit both the 'x' and 'y' attributes of an SVG element (rect) using a single jQuery call.
Now I know you can do this:
var incBy = 20;
$('#test').attr('x', function(i, val) {
return parseInt(val) + incBy;
});
which is fine for computing and editing single attributes, but how can I edit multiple attributes in this way?
You could try using a map with jQuery's attr method.
$('#test').attr(
{'x': editValue,
'y': editValue
});
function editValue(i, val) {
return parseInt(val) + incBy;
};
var incBy = 20;
$('#test').each(function () {
this.x += incBy;
this.y += incBy;
});
or, more elegantly, this (also has higher performance if you want to modify thousands of objects)
$.fn.extend({
modCoordsBy: function(amount) {
for (var i=0, j=this.length; i<j; i++) {
this[i].x += amount;
this[i].y += amount;
}
return this;
}
});
$('#test').modCoordsBy(20);
Apply range checks or type tests to x
and y
as you see fit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With