Skip to content

Instantly share code, notes, and snippets.

What would you like to do?

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>
circle { fill: lightgreen; stroke: #000; }
<script src=""></script>
var svg ="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"));
.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 ="body").append("div")
.style("float", "left")
function log(message) {
return function() {
.style("background", "#ff0")
.style("opacity", 1e-6)

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