If you are familiar with jQuery, then D3 should have a friendly attitude to it, since it has a similar API. In particular, with regard to the syntax .on(action, fn) for attaching an event listener to a DOM selection.
If you look at jsFiddle , I created one that implements a very basic implementation of what you are after, you can see this in movement in the 21st line of JS.
(function() { var svg = d3.select('svg'); function getRandom(min, max) { return Math.floor(Math.random() * (max - min) + min); } function drawCircle(x, y, size) { console.log('Drawing circle at', x, y, size); svg.append("circle") .attr('class', 'click-circle') .attr("cx", x) .attr("cy", y) .attr("r", size); } svg.on('click', function() { var coords = d3.mouse(this); console.log(coords); drawCircle(coords[0], coords[1], getRandom(5,50)); }); })();
The most important aspects of this fragment are in lines 18-20 ( .on(...) and d3.mouse(this) ). The on('click',..) event is bound to the svg element. When d3.mouse , the current region is called as an argument. Then it returns an array with x and y coordinates of the mouse event. This information is then passed to drawCircle along with a random radius to draw a circle on the current SVG canvas.
I advise you to take jsFiddle and play a game !
Gordyd
source share