Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
stopPropagation

This demonstrates how stopPropagation can be used to stop an event from propagating up the DOM tree, in response to a Stack Overflow question.

The mousedown event for the circle is prevented from propagating to the parent SVG element.

Note how a click gesture generates mousedown, mouseup and click events, in that order.

Note also that preventing the mousedown event from propagating is not sufficient to prevent the click event from propagating too. This must be done in a click event listener.

<!DOCTYPE html>
<style>
circle { fill: lightgreen; stroke: #000; }
</style>
<body>
<script src="http://d3js.org/d3.v2.min.js"></script>
<script>
var svg = d3.select("body").append("svg")
.style("float", "left")
.attr("width", 480)
.attr("height", 480)
.on("mousedown", log("mousedown svg"))
.on("mouseup", log("mouseup svg"))
.on("click", log("click svg"));
svg.append("circle")
.attr("cx", 240)
.attr("cy", 240)
.attr("r", 200)
.on("mousedown", function() { d3.event.stopPropagation(); })
.on("mousedown.log", log("mousedown circle"))
.on("mouseup", log("mouseup circle"))
.on("click", log("click circle"))
var div = d3.select("body").append("div")
.style("float", "left")
function log(message) {
return function() {
div.append("p")
.text(message)
.style("background", "#ff0")
.transition()
.duration(2500)
.style("opacity", 1e-6)
.remove();
};
}
</script>
@haydenw1

This comment has been minimized.

Copy link

@haydenw1 haydenw1 commented Jun 24, 2015

can you explain to me why you use "mousedown.log" (line 21) ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment