D3 How to trigger an event on an object behind the text
I am drawing A rect
and text
on svg.
To show text
, we first create rect
.
I add mouse click event
torect
when i click on the text it seems that rect is not selected because rect is behind the text, so the text is selected frist.
I need to choose to fire an event on mouse click inside rect
.
How can I do it?
Thank!
You can see that when you click on the text, the rectangle is not clicked.
var data = ["TEXT SAMPLE TEXT SAMPLE TEXT SAMPLE"];
var svg = d3.select("svg");
var bar = svg.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(100,100)"; });
bar.append("rect")
.attr("width", 200)
.attr("height", 50)
.style("fill", "#f00")
.on("click", function (d) {
alert("text");
});
bar.append("text")
.attr("x", 10)
.attr("y", 25)
.attr("dy", "-.35em")
.text(function(d) { return d; });
source to share
You can attach style to text to ignore mouse events. Here's an example:
Style:
.bar-text {
pointer-events: none;
}
Modified code:
bar.append("text")
.attr("x", 10)
.attr("y", 25)
.attr("class", "bar-text") // add class
.attr("dy", "-.35em")
.text(function(d) { return d; });
source to share