Skip to content

Instantly share code, notes, and snippets.

@Andrew-Reid
Last active March 17, 2017 03:10
Show Gist options
  • Save Andrew-Reid/f5b4227c93d197d69cf73e62c73afef3 to your computer and use it in GitHub Desktop.
Save Andrew-Reid/f5b4227c93d197d69cf73e62c73afef3 to your computer and use it in GitHub Desktop.
d3v3 Managing Click and Mouseover events in maps
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<html>
<head>
<style>
.region {
stroke: #fff;
fill: #005DAA;
}
.hover {
fill: yellow;
}
.selected{
stroke: #fff;
fill: orange;
}
#regName{
position: absolute;
top: 150px;
height: 22px;
width: 250px;
padding: 3px;
text-align:center;
}
</style>
</head>
<body>
<div id="map" style="text-align:center">
</div>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/queue-async/1.0.7/queue.js"></script>
<script type="text/javascript">
var width = 960,
height = 400,
centered;
var projection = d3.geo.albers()
.rotate([100,0])
.center([0,35])
.scale(800)
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("#map").append("svg")
.attr("width", width)
.attr("height", height);
queue()
.defer(d3.json, "data.json")
.await(ready);
function ready(error, us) {
svg.append("g")
.selectAll("path")
.data(topojson.feature(us, us.objects.us_eco_l3).features)
.enter()
.append("path")
.attr("d", path)
.attr("class", "region")
.on("mouseover", function (d) {
d3.select(this).attr("class", "region hover");
d3.select(this).on("mouseout", function(d) {
d3.select(this).attr("class", "region");
})
})
.on("click", function (d) {
svg.selectAll('path').attr('class','region'); // ensure every other feature is set to default
d3.selectAll('path').on("mouseover", function (d) { // add a mouseover event to every feature in order to get the last one clicked
d3.select(this).attr("class", "region hover");
d3.select(this).on("mouseout", function(d) {
d3.select(this).attr("class", "region"); // add a mouseout event to every feature on mouseover
});
});
d3.select(this).on("mouseout", null); // cancel mouseover out events for the clicked feature.
d3.select(this).on('mouseover',null);
d3.select(this).attr('class','selected');
});
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment