Aydin Özcan Aydin Özcan - 5 months ago 8
Javascript Question

Cannot protect the color of my svg when using mouseover method

I have some circles created in for loop and I want to change the color of these circles to red when mouse hovers over them. But when mouse loses the focus on these circles, I want them to protect the color they had before mouse hovered over them. But since the circles are created by for loop, I am not sure about how to do that.

The arrays are :

analyzedUnique = [34675791162, 10132910658, 10588895486, 10609894726, 14794759174, 1790587656, 18895624430, 3610288229, 4170058208, 5550074705, 7600064469]

[1790587656: "blue", 3610288229: "orange", 4170058208: "blue", 34675091162: "blue", 10132910658: "orange", 10588895486: "orange", 10609894726: "orange", 14794759174: "blue"…]

checkCustomer array is the numbers of people with a color assigned to them stating if the customer is an engineer.

for (i = 0; i < numberOfCirclesShown - 2 ; i++) {

var circle = svg.append("circle")

.attr("cx", circleR + r - r * cosDegrees(alpha * (i+1)))

.attr("cy", firstCircleY - r * sinDegrees(alpha * (i+1)))

.attr("r", circleR)

.style("fill", checkCustomer[analyzedUnique[i+2]]);

circle.on("mouseover", function(){d3.select(this).style("fill", "red");})

.on("mouseout", function(){d3.select(this).style("fill", **MUST PROTECT THE COLOR IT HAD**);});


I have searched internet but could not get a result. Thanks in advance.
Image : The visualization is here


In your case I'd use the .classed() attribute


    .on("mouseover", function(){d3.select(this).classed("fillCircle", true);})
    .on("mouseout", function(){d3.select(this).classed("fillCircle", false);});

and your css would be:

    fill: red !important;

if you use it like this, you will add the class on hover and remove it on mouseout