popover click off to close (AND open another popover, if a different node is clicked)

See this codepen for a demo of the popovers when you click on a blue node.

I am trying to make the popover close functionality work like the following

  • If I click “off” (in some non-interactive space, the background page), close popover.
  • If I click another node when an existing popover is open, the existing popover will close and the new popover associated with the just-clicked node will open.

I’ve followed an implementation where an invisible “tooltip-overlay” appears, which supports the click-off to close functionality. But that won’t let me click on other nodes without first hiding the overlay.

clicking a node fires clicknode function, which displays the “tooltip” and the “tooltipBg”

  function clicknode(event, nodes) {
  const[x, y] = d3.pointer(event);
  tooltipBg.style("display", "block");
  tooltip
    .style("left", `${event.pageX}px`)
    .style("top", `${event.pageY}px`)
    .transition().duration(1).style("visibility", "visible")
    .transition().duration(300).style("opacity", 1)
    .style("display", "block");
     loadTooltipContent(nodes);
}

Thanks for any help you might have.