Reputation: 301
I'm trying to get a simple mouseover to work on some rectangles in d3. If I append the SVG to "body" everything works just fine (first line of code). If I change the select to ".chart1" instead of "body" the mouseovers don't work. Has anyone seen this before?
var chart = d3.select(".chart1").append("svg")
.attr("width", 250)
.attr("height", 50);
data = ["a", "b", "c",]
for(var i = 0; i < data.length; i++){
var rect = chart.append("rect")
.attr("x", 20*i)
.attr("y", 10)
.attr("width", 15)
.attr("height", 15)
chart.selectAll('rect')
.on("mouseover", function() {
d3.select(this)
.attr("opacity", .5)
})
.on("mouseout", function() {
d3.select(this)
.attr("opacity", 1)
});
jsfiddle: https://jsfiddle.net/jasonleehodges/um5f5ysv/
Upvotes: 0
Views: 145
Reputation: 32327
The problem is not because you are appending svg to body or div with class .chart1
The problem of mouseover not working is in here.
var chart = d3.select(".chart1").append("svg")
.attr("width", 250)
.attr("height", 50)
//.style("pointer-events", "none");//WHY DISABLE MOUSE EVENT ON SVG
Fix would be to remove .style("pointer-events", "none");
and it will work on all the cases without any anomaly.
Working code here
On another note you should not use a for loop, well that's not the d3 way(as put by @Gerardo Furtado).
so your code with for
:
for(var i = 0; i < data.length; i++){
var rect = chart.append("rect")
.attr("x", 20*i)
.attr("y", 10)
.attr("width", 15)
.attr("height", 15)
instead should be
var rect = chart.selectAll("rect").data(data).enter().append("rect")
.attr("x", function(d,i){return 20*i})
.attr("y", 10)
.attr("width", 15)
.attr("height", 15)
.attr("fill", "#cc004c")
.attr("title","NBC")
.attr("data-toggle","tooltip")
working code here
Upvotes: 1