Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.js when click outside the elements, hide the element

I have some tootips in my page. There is one tooltip(div) contains a input box and a button. I want to click outside the tooltip and then hide the tooltip. I tried this:

d3.select("body")
.on("click",function(){
    d3.select("#tooltip")
    .classed("hidden",true);
});

This works, but when I click the input box want to input some value, the tooltip still hide. How can I hide the tooltip only when I click outside the tooltip?

I also tried:

d3.select("body").filter().on("click",function(){})

But I don't how it works, I cannot select all elements except the tooltip(div).

like image 825
Yawei Avatar asked Apr 06 '16 04:04

Yawei


1 Answers

Here is a solution:

var tooltip = d3.select("#tooltip");
var tooltipWithContent = d3.selectAll("#tooltip, #tooltip *");

function equalToEventTarget() {
    return this == d3.event.target;
}

d3.select("body").on("click",function(){
    var outside = tooltipWithContent.filter(equalToEventTarget).empty();
    if (outside) {
        tooltip.classed("hidden", true);
    }
});

JSFiddle: https://jsfiddle.net/LukaszWiktor/53yok58w/

like image 80
Lukasz Wiktor Avatar answered Sep 22 '22 16:09

Lukasz Wiktor