Skip to content

Instantly share code, notes, and snippets.

@hlucasfranca
Forked from jasondavies/README.md
Last active August 29, 2015 14:26
Show Gist options
  • Save hlucasfranca/c557b969fe46cea9383e to your computer and use it in GitHub Desktop.
Save hlucasfranca/c557b969fe46cea9383e to your computer and use it in GitHub Desktop.
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment