Accepted answer

If you are familiar with JQuery then D3 should have a friendly feel to it, as it shares a similar API. Specifically in regards to .on(action, fn) syntax for attaching an event listener to a DOM selection.

If you check out the jsFiddle I have created which implements a very basic implementation of what you are after then you can see this in motion in 21 lines of JS.

(function() {
    var svg ='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);
            .attr('class', 'click-circle')
            .attr("cx", x)
            .attr("cy", y)
            .attr("r", size);

    svg.on('click', function() {
        var coords = d3.mouse(this);
        drawCircle(coords[0], coords[1], getRandom(5,50));

The most important aspects of this snippet are on lines 18-20 (.on(...) and d3.mouse(this)). The on('click',..) event is attached to the svg element. When a click occurs d3.mouse is called with the current scope as its argument. It then returns an array with x and y coords 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 the jsFiddle and have a play!

Related Query

More Query from same tag