0

I don't understand why my click event handler doesn't work. I know the event handler is running because I can see output for the three console.log() statements. The trouble is that the click event does not change the fill color. My code is all contained in one Observable notebook cell. I am using d3 version 7.3.0.

chart = {

  const height = 200;
  
  const svg = d3.create("svg")
      .attr("width", width)
      .attr("height", height);

  let my_circles = svg
    .selectAll("circle")
    .data(d3.range(10))
    .enter()
    .append("circle")
      .attr("cx", d => d * 50)
      .attr("cy", height / 2)
      .attr("r", d => Math.random() * 20)
      .attr("fill", "blue");

  my_circles
    .on("click", (event, d) => {
          console.log(event);
          console.log(d);
          console.log(d3.select(this));
          d3.select(this).attr("fill", "orange");
      });

  return svg.node();
}

Help is appeciated and thank you.

Paul

user3344266
  • 69
  • 1
  • 7
  • It looks like you're expecting `this` to refer something. What's the output of that third console.log say? – Thomas Feb 07 '22 at 06:39
  • This is the output. I don't know how to interpret it. ```qn {_groups: Array(1), _parents: Array(1)} _groups: Array(1) 0: [svg] length: 1 [[Prototype]]: Array(0) at: ƒ at() concat: ƒ concat() constructor: ƒ Array() copyWithin: ƒ copyWithin() entries: ƒ entries() every: ƒ every() fill: ƒ fill() filter: ƒ filter() find: ƒ find() findIndex: ƒ findIndex() findLast: ƒ findLast() findLastIndex: ƒ findLastIndex() flat: ƒ flat() flatMap: ƒ flatMap() forEach: ƒ forEach() includes: ƒ includes() indexOf: ƒ indexOf() join: ƒ join() keys: ƒ keys() lastIndexOf: ƒ lastIndexOf() ``` – user3344266 Feb 07 '22 at 07:44
  • 2
    arrow functions do not create *this*; you might replace it with function (event, d) {…}, or use event.target: d3.select(event.target).attr("fill", "orange"); – Fil Feb 07 '22 at 07:48
  • Thank you! I tried both of those things. It works if I keep the arrow function and change "this" to "event.target". If I change it to a regular function it works with "this" or "event.target". – user3344266 Feb 07 '22 at 22:46

0 Answers0