Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StopPropagation() with SVG element and G

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");
}
like image 608
Elijah Avatar asked Jul 26 '12 17:07

Elijah


People also ask

What does the event stopPropagation () method do?

stopPropagation() The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.

What is event stopPropagation () Angular?

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

What's the difference between event preventDefault () and event stopPropagation () methods?

preventDefault() prevents the default browser behavior for a given element. stopPropagation() stops an event from bubbling or propagating up the DOM tree.

What is the use of stopPropagation method for stopping event bubbling )?

stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.


1 Answers

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.

like image 84
Jason Davies Avatar answered Sep 22 '22 21:09

Jason Davies