Reputation: 784
I have lots of rects automatically created on a Raphael canvas, for simplicity this code only uses two:
for (i = 0; i < 2; ++i) {
var square = paper.rect(0 + 100*i, 0, 70, 70);
square.node.setAttribute('id', '_' + i);
square.node.setAttribute('class', 'foo');
}
which creates this chunk below (as seen with view selection source in Firefox):
<svg height="560" width="560" version="1.1" xmlns="http://www.w3.org/2000/svg"><desc>Created with Raphael</desc><defs></defs><rect class="foo" id="_0" stroke="#000" fill="none" ry="0" rx="0" r="0" height="70" width="70" y="0" x="0"></rect><rect class="foo" id="_1" stroke="#000" fill="none" ry="0" rx="0" r="0" height="70" width="70" y="0" x="100"></rect></path></svg>
The css class indicates the color to fill. I would like to change the class of the each rect, individually, using a click function. I would need something like:
function change_class() {
//something here
}
From everything I've read, this is done using .node
, but here I don't have a separate variable for each rect
, given that square
was overwritten on each iteration of the for()
loop.
One way to do this would be to push all rects to an array, like this:
squares = [];
for (i = 0; i < 2; ++i) {
var square = paper.rect(0 + 100*i, 0, 70, 70);
square.node.idx = i;
square.node.setAttribute('class', 'foo');
squares.push(square);
}
I could then change the class directly via:
squares[0].node.setAttribute('class', 'other');
BUT... I still don't know how to do it via the general function change_class()
... I need something like:
$('rect').click(function() {
change_class(); // the click function should pass "$(this)" to change_class ?
});
What would be the right jQuery + Raphael method to do this?
Thanks in advance, Adrian
Upvotes: 2
Views: 1449
Reputation: 3117
If you want to click the box itself to change its color, you don't need jQuery, you can use Raphael's built-in event method, and refer to the rectangle as this
, like so:
rect.click( function () {
this.node.setAttribute('class', 'newClass');
});
Upvotes: 2