jQuery addClass example
Change class name on click in jQuery
by vrluckyin India
HTML
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
<button>Change color</button>
</div>
CSS
.background {
fill: none;
pointer-events: all;
}
#states {
fill: #aaa;
}
#states .active {
fill: orange;
}
#state-borders {
fill: none;
stroke: #fff;
stroke-width: 1.5px;
stroke-linejoin: round;
stroke-linecap: round;
pointer-events: none;
}
JavaScript
var width = 960,
height = 500,
centered;
var projection = d3.geo.albersUsa()
.scale(1070)
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", clicked);
var g = svg.append("g");
var dataObjects= [
{d:"M239 0 h 320 v 80 h -320 Z", fill:"#fff2cc", stroke:"black"},
{d:"M239 120 h 320 v 80 h -320 Z", fill:"#a9c4eb", stroke:"black"},
{d:"M239 240 h 320 v 80 h -320 Z", fill:"#f8cecc", stroke:"black"},
{d:"M659 280 h 120 v 320 h -120 Z", fill:"#fff2cc", stroke:"black", transform:"rotate(-23,719,440)"},
{d:"M49 290 h 120 v 320 h -120 Z", fill:"#99ffff", stroke:"black", transform:"rotate(19,109,450)"},
{d:"M169 480 h 230 v 80 h -230 Z", fill:"#a9c4eb", stroke:"black"},
{d:"M424 480 h 230 v 80 h -230 Z", fill:"#a9c4eb", stroke:"black"},
{d:"M79 680 h 680 v 40 h -680 Z", fill:"#cc0066", stroke:"black"}
]
g.append("g")
.attr("id", "states")
.selectAll("path")
.data(dataObjects)
.enter().append("path")
.attr("d", function(d){console.log('d',d.d)})
.on("click", clicked);
g.append("path")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("id", "state-borders")
.attr("d", path);
function clicked(d) {
var x, y, k;
if (d && centered !== d) {
var centroid = path.centroid(d);
x = centroid[0];
y = centroid[1];
k = 4;
centered = d;
} else {
x = width / 2;
y = height / 2;
k = 1;
centered = null;
}
g.selectAll("path")
.classed("active", centered && function(d) { return d === centered; });
g.transition()
.duration(750)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
...