Reputation: 63
I'm using D3 V4 and am trying to get the ID of the object that is clicked on. Heck, I'd love to see any attribute value returned (d, fill, class, etc). Instead I get null returned, no matter the attribute. Code below.
d3.json("0267_02_combine.json", function(json) {
var features = json.features;
var path = d3.geoPath()
.projection(projection.fitExtent([[0, 0], [w, h]], json));
svg.selectAll(".room")
.data(json)
.enter().append("path")
.attr("class", "room")
.attr("d", path)
.attr("fill","lightblue")
.attr("id", function(d){
return d.properties.loc;
});
svg.on("click", function() {
console.log(d3.select(this)); //I see stuff! Yay!
console.log(d3.select(this).attr("fill")); //returns null
console.log(d3.select(this).attr("id")); //returns null
console.log(d3.select(this).attr("class")); //returns null
var coords = d3.mouse(this);
console.log(coords); //returns SVG coordinates
console.log(projection.invert(d3.mouse(this))); //returns lat/lon
})
});
Upvotes: 1
Views: 753
Reputation: 20821
Are you sure the selected element you are attaching the click handler to has a fill, class or id?
Try adding your click handler to the path instead.
d3.json("0267_02_combine.json", function(json) {
var features = json.features;
var path = d3.geoPath()
.projection(projection.fitExtent([[0, 0], [w, h]], json));
var path = svg.selectAll(".room")
.data(json)
.enter().append("path")
.attr("class", "room")
.attr("d", path)
.attr("fill","lightblue")
.attr("id", function(d){
return d.properties.loc;
});
path.on("click", function() {
console.log(d3.select(this)); //I see stuff! Yay!
console.log(d3.select(this).attr("fill")); //returns null
console.log(d3.select(this).attr("id")); //returns null
console.log(d3.select(this).attr("class")); //returns null
var coords = d3.mouse(this);
console.log(coords); //returns SVG coordinates
console.log(projection.invert(d3.mouse(this))); //returns lat/lon
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Upvotes: 3