Let's go back to the path style color when clicking on d3.select (this)

I have functiona map d3.js.

I used d3.select(this).style('fill', 'red');to change the color when the user clicks a button svg path.

The color changes, but I want to update the color svg pathto an older one when I click on a new path.

This is the function I used:

.on('click', function(d) {
        d3.select(this).style('fill', 'red')
            .style('stroke-width', 3);
        var year = $(".year-label").text();
        var infoYear = 'yr' + year;
        var counts = [];
        for (i = 1984; i <= 2016; i++){
            cnts = 'yr' + i.toString();
            counts.push(d.properties[cnts]);
        }
        console.log(counts);
        console.log(counts.length);

        $('.text-name').empty();
        var nameit = d.properties.city;
        $('.text-name').append(nameit);
});

Each path is unique id. So I tried this function without any results:

.on('click', function(d) {
    d3.select('._' + d.geoid).this.style('fill', 'red');

I am missing an element, so I am trying to solve it with slight changes in this line. However, this does not work.

This is a picture of this problem:

enter image description here

Thanks in advance for your support!

+4
source share
1 answer

. : ?

, , , () :

d3.selectAll("path").style("fill", "gray")
d3.select(this).style("fill", "red")

- :

var data = d3.range(4);
var svg = d3.select("body")
  .append("svg")
  .attr("width", 400)
  .attr("height", 100);

var circles = svg.selectAll(".circles")
  .data(data)
  .enter()
  .append("circle");

circles.attr("cy", 50)
  .attr("r", 50)
  .attr("cx", function(d){ return 50 + d*100})
  .attr("fill", "gray")
  .attr("cursor", "pointer");

circles.on("click", function(){
  d3.selectAll("circle").attr("fill", "gray");
  d3.select(this).attr("fill", "red");
});
<script src="https://d3js.org/d3.v4.min.js"></script>
Hide result

, , , .

, , , , . . , , , , :

prevElem = d3.select(this);
prevColour = d3.select(this).attr("fill");

, , :

if(prevElem){prevElem.attr("fill", prevColour);};

:

var data = d3.range(4);
    var svg = d3.select("body")
      .append("svg")
      .attr("width", 400)
      .attr("height", 100);

var prevElem, prevColour;

    var circles = svg.selectAll(".circles")
      .data(data)
      .enter()
      .append("circle");

    circles.attr("cy", 50)
      .attr("r", 50)
      .attr("cx", function(d){ return 50 + d*100})
      .attr("fill", function() {
    return "hsl(" + Math.random() * 360 + ",100%,50%)";
    })
      .attr("cursor", "pointer");

    circles.on("click", function(){
      if(prevElem){prevElem.attr("fill", prevColour);};
      prevElem = d3.select(this);
      prevColour = d3.select(this).attr("fill");
      d3.select(this).attr("fill", "red");
    });
<script src="https://d3js.org/d3.v4.min.js"></script>
Hide result
+4

Source: https://habr.com/ru/post/1656281/


All Articles