I'm trying to get a simple mouse event to work with D3.js (v5.7.0) But for some reason it doesn't pass the EVT object to the function.
This is my current code:
const svg = d3.select("svg");
const width = +$('#d3canvas #d3container').width();
const height = +$('#d3canvas #d3container').height();
console.log([width, height]);
svg.append("rect")
.attr("fill", "none")
.attr("pointer-events", "all")
.attr("width", width)
.attr("height", height)
.call(d3.zoom().on("zoom", zoom));
function zoom() {
g.attr("transform", d3.event.transform);
}
const g = svg.append("g")
.attr("width", width)
.attr("height", height);
g.append("circle")
.style("fill", "black")
.attr("r", 40)
.attr("cx", 50)
.attr("cy", 20)
.on("mousedown", test);
function test(evt) {
console.log(evt);
}
html,
body {
margin: 0px;
padding: 0px;
width: 100%;
height: 100%;
}
#d3canvas {
width: 100%;
height: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="d3canvas">
<svg width="100%" height="800px" id="d3container"></svg>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
</body>
</html>
So now if I click on the circle the console writes Undefined. I found a similar question here (the mistake was a z-index in css which isn't the case for me)
I do see that that question uses d3.selectAll if I change my code to look like this it still won't work:
g.append("circle")
.style("fill", "black")
.attr("r", 40)
.attr("cx", 50)
.attr("cy", 20);
d3.selectAll("circle").on("mousedown", test);
I can get it to work by programmatically adding an eventListener to the circle like so:
let circle = g.append("circle")
.style("fill", "black")
.attr("r", 40)
.attr("cx", 50)
.attr("cy", 20);
circle._groups[0][0].addEventListener("mousedown", test);
But I'm not sure if this is the right way to do it.
Question: Why isn't the mouse event object being passed to the test function? And what is the right / better way to do something like this?