Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute and edit multiple attributes in a single jQuery call

Tags:

jquery

attr

edit

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?

like image 647
Steve Avatar asked Feb 24 '23 17:02

Steve


2 Answers

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;
};
like image 67
Amrit Avatar answered Feb 26 '23 06:02

Amrit


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.

like image 31
Tomalak Avatar answered Feb 26 '23 06:02

Tomalak