Why does the click event work the first time, but subsequent clicks only affect in last DOM node?

issue

I encountered an issue while using D3.js. I have two functions, unexpectedCode and expectedCode, which are supposed to draw some circles in an SVG and change their color when clicked. The click event in expectedCode works fine, but in unexpectedCode, it only works the first time. Subsequent clicks only change the color of the last circle. I’m new to D3.js, and this is quite confusing for me. I would really appreciate it if you could help me analyze the problem!

core code

const unexpectedCode = (selection) => {
      selection
        .append("g")
        .selectAll("circle")
        .data(dots)
        .join((enter) => {
          enter
            .append("circle")
            .style("cursor", "pointer")
            .attr("id", (d) => "circle" + d)
            .attr("cx", (d) => d * 32)
            .attr("cy", 20)
            .attr("r", (d) => d * 5)
            .call((circle) => {
              circle.on("click", (e, d) => {
                console.log("d", d);
                enter
                  .select(`#circle` + d)
                  .transition()
                  .attr("fill", "red")
                  .transition()
                  .attr("fill", "black");
              });
            });
        });
    };
const expectedCode = (selection) => {
      selection
        .append("g")
        .selectAll("circle")
        .data(dots)
        .join((enter) => {
          enter
            .append("circle")
            .style("cursor", "pointer")
            .attr("id", (d) => "circle" + d)
            .attr("cx", (d) => d * 32)
            .attr("cy", 20 + yOffset)
            .attr("r", (d) => d * 5)
            .each((datum) => {
              enter.select(`#circle` + datum).call((circle) => {
                circle.on("click", () => {
                  circle
                    .transition()
                    .attr("fill", "red")
                    .transition()
                    .attr("fill", "black");
                });
              });
            });
        });
    };

reproduction

codesandbox

what I want

Explain the behavior or logic behind unexpectedCode.

new discovery

The issue seems to be with enter.select. You can try using this demo, but I still don’t understand why. In my understanding, since I added elements to enter, I should be able to find these circles within enter, and it should be faster than using d3.select. However, in reality, using enter.select, my code doesn’t work correctly.

circle.on("click", (e, d) => {
  console.log("d", d);
  // use d3.select can work well
  // d3.select(`#circle` + d)
  //   .transition()
  //   .attr("fill", "red")
  //   .transition()
  //   .attr("fill", "black");
  enter
    .select(`#circle` + d)
    .transition()
    .attr("fill", "red")
    .transition()
    .attr("fill", "black");
});

I would normally suggest delegation but in this case it is more readable to bind the event handler immediately after appending the circle elements without re-selecting or iterating and more efficient because it avoids unnecessary re-selections (enter.select() inside .each()) and re-iterations over the data.

codesandbox

const fixedUnexpectedCode = (selection) => {
  selection
    .append("g")
    .selectAll("circle")
    .data(dots)
    .join((enter) => {
      const circle = enter
        .append("circle")
        .style("cursor", "pointer")
        .attr("id", (d) => "circle" + d)
        .attr("cx", (d) => d * 32)
        .attr("cy", 20)
        .attr("r", (d) => d * 5);

      // Attach click event directly to the circle selection
      circle.on("click", (e, d) => {
        console.log("d", d);
        d3.select(`#circle${d}`)
          .transition()
          .attr("fill", "red")
          .transition()
          .attr("fill", "black");
      });
    });
};

2

I’m not sure I follow your code and event binding. A more canonical way to do this with d3 would be:

const unexpectedCode = (selection) => {
  selection
    .append("g")
    .selectAll("circle")
    .data(dots)
    .join((enter) => {
      enter
        .append("circle")
        .style("cursor", "pointer")
        .attr("id", (d) => "circle" + d)
        .attr("cx", (d) => d * 32)
        .attr("cy", 20)
        .attr("r", (d) => d * 5)
        .on("click", function() {
          d3.select(this)
            .transition()
            .attr("fill", "red")
            .transition()
            .attr("fill", "black");
        })
    });
};

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật