I draw A rect
and text
on svg.
In order to show text
, I render rect
first.
I add mouse click event
to rect
when I click the text, it seems the rect is not selected, because rect is behind text, so text is selected frist.
I need to select trigger the event when mouse click inside the rect
.
How should I do?
Thanks!
Fiddle
You can see, when you mouse click on the text, the rect 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; });
The D3 way of fetching the event object is by calling d3.event. For example, in the map bellow you can click on the map to create pointers, and CTRL + click on pointers to remove them: Just like with the native JavaScript object, you can use d3.event.ctrlKey to check if the CTRL key is pressed:
As in all other libraries, D3 also supports built-in events and custom events. We can bind an event listener to any DOM element using d3.selection.on () method. The on () method adds an event listener to all selected DOM elements. The first parameter is an event type as string such as "click", "mouseover" etc.
D3 depicts an event when it occurs and stores it in the d3.event variable. This is a state variable and can be used in the callback function of the listener authorized with the operator's d3 selection stage.
Event Handling in D3.js. D3 depicts an event when it occurs and stores it in the d3.event variable. This is a state variable and can be used in the callback function of the listener authorized with the operator’s d3 selection stage. The latest d3 running just after the JavaScript callback function has been completed.
You can attach a style to the text to ignore mouse events. Here is the 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; });
Attach the handler to the g
element. Complete demo here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With