Computing and editing multiple attributes in a single jQuery call

I need to compute a new one and edit the "x" and "y" attributes of an SVG (rect) element using a single jQuery call.

Now I know that you can do this:

var incBy = 20; $('#test').attr('x', function(i, val) { return parseInt(val) + incBy; }); 

which is great for computing and editing individual attributes, but how can I edit multiple attributes this way?

+4
source share
4 answers

If in doubt, you can also do this on one line:

 $('#test').attr('x', myFunction).attr('y', myFunction); function myFunction(i, val) { return parseInt(val) + incBy; } 

Or abstract it more and pass the attributes you want to apply to a separate function

 process('x', 'y'); function process() { for (var i = 0; i < process.arguments.length; i++) $('test').attr(process.arguments[i]), myfunction); function myFunction(i, val) { return parseInt(val) + incBy; } } 

It depends on how far you want to go. You can enable the function that will be called in the parameters, and selection criteria.

0
source

You can try using the map using the jQuery attr method.

 $('#test').attr( {'x': editValue, 'y': editValue }); function editValue(i, val) { return parseInt(val) + incBy; }; 
+4
source
 var incBy = 20; $('#test').each(function () { this.x += incBy; this.y += incBy; }); 

or, more elegantly, this (also has better performance if you want to change 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 enter tests on x and y as you see fit.

+3
source

I'm not sure if it’s possible to do this with several attributes, but if you are looking for a way to prevent code duplication, you can reorganize the anonymous function.

 $('#test').attr('x', myFunction); $('#test').attr('y', myFunction); function myFunction(i, val) { return parseInt(val) + incBy; } 
+1
source

All Articles