Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch the mouse events in multiple layers?

Now I am struggling with one problem. Please have a look at the codes shown below, I want to implement two functions,one is zooming in the container(i.e. zooming all the nodes in the container), the second is to alert the id of the node in the container, when the mouse is over it.

But, when I set the value of "pointer-event" of rect to all, the zooming is fine but the nodes can't catch the mouseover event. When I set the value to "none", the nodes can catch the mouseover event but the zooming doesn't work. It seems that "nodes" and "rect" are in different layers, thus can't catch the events at the same time.

Anybody knows how to fix this? Thanks in advance.

    var zoom = d3.behavior.zoom()
        .scaleExtent([0.1, 10])
        .on("zoom", zoomed);
    function zoomed() {
        container.attr("transform", "translate(" + d3.event.translate +")scale(" + d3.event.scale +")");
    }

    var container = svg.append("g");
    var rect = svg.append("rect")
        .attr("width", width/2)
        .attr("height", height)
        .style("fill", "none")
        .style("pointer-events", "all")
        .call(zoom);
    var node = container.append("g")
        .attr("class", "nodes")
        .selectAll(".node")
        .data(nodes)
        .enter().append("g")
        .attr("class", "node")
        .attr("id",function(d){return d.userID});
    node.on("mouseover", function(d) {      
        alert(d.userID);
    });        
like image 645
Maytree23 Avatar asked Nov 19 '25 13:11

Maytree23


1 Answers

The problem is, you are appending the container div before the background rectangle. In this case, the target of mouse events will be the rectangle since the container group and nodes lies underneath that element. Try this code.

var zoom = d3.behavior.zoom()
    .scaleExtent([0.1, 10])
    .on("zoom", zoomed);

function zoomed() {
    container.attr("transform", "translate(" + d3.event.translate +")scale(" + d3.event.scale +")");
}

var rect = svg.append("rect") //Append background rect first
    .attr("width", width/2)
    .attr("height", height)
    .style("fill", "none")    
    .style("pointer-events", "all")    
    .call(zoom);

var container = svg.append("g"); //Then append the container group

var node = container.append("g")
    .attr("class", "nodes")
    .selectAll(".node")
    .data(nodes)
    .enter().append("g")
    .attr("class", "node")
    .attr("id",function(d){return d.userID});

node.on("mouseover", function(d) {      
    alert(d.userID);
});       
like image 86
Gilsha Avatar answered Nov 22 '25 03:11

Gilsha