Toggle raphael object's colour on click

241 views Asked by At

I've created a rectangle using raphael.js. var rect = paper.rect(x,y,width,height); Assume that x, y, width and height has some values. I'd like to add in a mouse click handler that'll toggle the rectangle's "fill" colour on click.

Other than using 'if...else...', how can I toggle the colour between 'red' and 'green' on click?? something that'll replace "if...else..." in the following function:

var colour = 'red';
rect.node.onclick = function(){
    if (colour == 'red') colour = 'green';
    else if (colour == 'green') colour = 'red';
    this.setAttribute("fill",colour);
}

UPDATE:

var fill = 'red';
rect.node.onclick = function(){
    fill  = (fill == 'red') ? 'green': 'red';
    console.log(fill);
    this.setAttribute("fill", fill);
}

I can now see my fill toggling between red and green on my console. but it doesn't change the actual rectangle's colour.

2

There are 2 answers

0
Cymen On BEST ANSWER

How about:

rect.node.onclick = function(){
    var currentColor = this.getAttribute('fill');
    var targetColor = (currentColor === 'red') ? 'green' : 'red';
    this.setAttribute("fill", targetColor);
}

That should work even if no fill color is set.

0
Ian On

Feels like if you are using Raphael, it makes sense to use Raphs methods, and avoid things like Raphaels internal accessors like node(). So you could rewrite it as

rect.click( function() {
    this.attr({ fill: this.attr('fill') == 'green' ? 'red' : 'green' }); 
});