Handling mouse events when using d3-brush


I have read several articles on related topics, but I am still not sure how to properly handle some mouse / touch events (e.g. to update a tooltip) when using d3.brush().

The code below seems to do the job, but the fact that I need to handle some events manually (e.g. hide the tooltip when brushing outside the chart) makes me think that my approach may not be correct.

Apologies for not providing a more concise example. Here is the general pattern :

const brush = d3.brushX()
    .extent([[margin.left, margin.top], [width - margin.right, height - margin.bottom]])
    .on("start", () => {
        // For touch screens :
        // Hide remaining tooltips on the page (multiple charts page)
    .on("brush", mouseMoved)
    .on("end", () => {
        // Hide tooltip and process selection

const context = svg.append("g")
    .attr("class", "brush")
    .on("touchmove mousemove", mouseMoved)
    .on("touchend mouseleave", () => {
        // Hide tooltip

function mouseMoved() {
    // Check if inside the chart
    // Hide or unhide+update tooltip accordingly

Any advice would be appreciated.