score:2

Accepted answer

Reason your event fires only for first bar and not the dynamic ones is because of the way you added your event listener.

Your way only puts events on elements already present on the page (they are in DOM structure). Any new elements will not have this event listener tied to them.

You can make a quick check for this by putting your code in function like

function setListeners() {
  svg.select(".bars").selectAll("rect").on("mouseover", function() {
    d3.select(this)
      .transition()
      .attr("fill", "red");
  })
}

After you add any new bars on the screen, add this function call and see if it works for all elements. If this is indeed the case, you need to write your event listener in a way it works for all elements, including dynamically added ones. The way to do that is to set the event to some of the parent DOM nodes and then checking if you are hovering on exactly the thing you want the event to fire.

Example:

$(document).on(EVENT, SELECTOR, function(){
    code;
});

This will put the event on the body and you can check then selector after it's triggered if you are over correct element. However it was a while since I worked with D3 and I'm not sure how D3, SVG and jQuery play together, last time I was doing it they had some troubles. In this case event should be mouseover, selector should be your rect bars and function should be what ever you want to run.

If everything else fails in case they won't cooperate, just use the function to set event listeners and call it every time after you dynamically add new elements.


Related Query

More Query from same tag