15

I created an SVG element with an .on("click") behavior and appended g elements with .on("click") and thought that I could use d3.event.stopPropagation() to keep the SVG click event from firing with the g click event. Instead, both events continue to fire. So I must be placing stopPropagation in the wrong place.

svg = d3.select("#viz").append("svg:svg")
    .attr("width", 800)
    .attr("height", 800)
    .on("mousedown", mousedown);

sites = svg.selectAll("g.sites")
    .data(json.features)
    .enter()
    .append("svg:g")
    .on("click", siteClick)
    ;

sites.append("svg:circle")                
    .attr('r', 5)
    .attr("class", "sites")
    ;

function mousedown() {
    console.log("mouseDown");
}

function siteClick(d, i) {
    d3.event.stopPropagation();
    console.log("siteClick");
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Elijah
  • 4,609
  • 3
  • 28
  • 36

1 Answers1

26

You seem to be mixing up the click and mousedown events. Calling stopPropagation will only prevent propagation of a single event at a time, and these are separate events.

Typically, a click gesture will cause mousedown, mouseup and click events, in that order.

You can keep the click event handler on the child elements and add a mousedown event handler with a stopPropagation call, and that should achieve what you're after.

Here is an example demonstrating its use in a similar situation to yours.

Jason Davies
  • 4,693
  • 30
  • 39
  • Hi Jason, I'm still not clear on how the code would look. I need the event on the to be a mousedown event and I need the event on the to be a click event. I updated sites to include the following but with no change: .on('mousedown', function(){ d3.event.sourceEvent.stopPropagation(); }) – Elijah Jul 27 '12 at 00:25
  • You need to use `d3.event.stopPropagation()`. Your code will not work, since `d3.event.sourceEvent` is undefined. I've added an example for you now, too. – Jason Davies Jul 27 '12 at 08:40
  • I forgot to mention that I tried event, event.source and event.target with no effect. I was just copypasting various stopPropagation() terminology used in other D3 demos. But your demo is great, and exactly what I need to understand it. – Elijah Jul 28 '12 at 02:16
  • Great link, explains it perfectly – Drenai Jul 16 '16 at 21:55