Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
88
rated 0 times [  92] [ 4]  / answers: 1 / hits: 34212  / 12 Years ago, thu, june 7, 2012, 12:00:00

I'm just starting playing around with d3, and was wondering how you could alternate the colors of a element upon clicking it.



This fiddle changes the color of the circle clicking it, but then I'd like to get the color back to being white after clicking again.



Current Code:



var sampleSVG = d3.select(#viz)
.append(svg)
.attr(width, 100)
.attr(height, 100);

sampleSVG.append(circle)
.style(stroke, gray)
.style(fill, white)
.attr(r, 40)
.attr(cx, 50)
.attr(cy, 50)
.on(click, function(){d3.select(this).style(fill, magenta);});

More From » d3.js

 Answers
303

Make yourself a toggle function and pass it into the click: http://jsfiddle.net/maniator/Bvmgm/6/



var toggleColor = (function(){
var currentColor = white;

return function(){
currentColor = currentColor == white ? magenta : white;
d3.select(this).style(fill, currentColor);
}
})();

[#85077] Wednesday, June 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzs

Total Points: 710
Total Questions: 113
Total Answers: 100

Location: Nepal
Member since Sat, Jul 18, 2020
4 Years ago
cruzs questions
Thu, Nov 26, 20, 00:00, 4 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
Sun, Aug 2, 20, 00:00, 4 Years ago
;