Search code examples
javascriptjquerycssd3.jssvg

D3 click event with multiple svg on one page


I have a webpage with two svg inserted via D3.js. I can add click events to the svg, which I have directly appended to the body. However I have another "floating" div above the first svg, where I append another svg. When trying to add click events, they do not fire.

I have also tried tracking the mouse position, but this only worked in the svg appended to the body, too.

Is there a way to be able to assign click listeners to the rect, that are inside the "floating" div?

I have the fiddle here: JsFiddle

I am trying, to change the color from black to white and vice versa, when clicked on a rect on top of the page. How is it possible?

I have also tried the jQuery approach..

Note that if you move your mouse on the second svg, you can actually drag and zoom in the first one, which is unwanted behaviour, too.


Solution

  • Here is an updated working JsFiddle that uses class toggling for achieving the desired effect. The relevant part of JS is here:

      d3.selectAll(".controlBarButton")
        .classed("white",function(d,i){return rule[i] === "none"})
        .on("click",function(){
           d3.select(this).classed("white",!d3.select(this).classed("white"));
        });
    

    I also commented out previous style settings to white on the lines 68 and 79. I added css rules for setting black and white fills according to toggling white class and removed pointer-events: none css rule that blocked all the mouse events on the control bar.