Skip to content

Instantly share code, notes, and snippets.

@chrispruitt
Last active August 15, 2019 17:08
Show Gist options
  • Save chrispruitt/f34b37e0efb470193445a9bfd2683249 to your computer and use it in GitHub Desktop.
Save chrispruitt/f34b37e0efb470193445a9bfd2683249 to your computer and use it in GitHub Desktop.
Simple Toggle Button
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
var svg = d3.select("body").append("svg")
.attr("width", 300)
.attr("height", 300)
function drawToggleBtn(active = false) {
let width = 100;
let height = 50;
let cMargin = 8;
let cRadius = (height / 2) - cMargin;
let x = 150;
let y = 150;
let cX = x + cRadius + cMargin;
let cY = y + cRadius + cMargin;
let activeCX = x + width - cMargin - cRadius;
let t = function () {
return d3.transition().duration(1000);
};
let className = 'toggle-btn';
let initialFill = "#D0D0D0";
let activeFill = "#4F4DC7";
let cFill = "#ffffff";
let rect = svg.append("rect")
.attr("class", className)
.attr("x", x)
.attr("y", y)
.attr("fill", initialFill)
.attr("width", width)
.attr("height", height)
.attr("rx", height / 2)
.style("cursor", "pointer");
let circle = svg.append("circle")
.attr("class", 'toggle-btn-circle')
.attr("cx", cX)
.attr("cy", cY)
.attr("fill", cFill)
.attr("r", cRadius)
.style("pointer-events", "none");
if (active) {
rect.attr("fill", activeFill)
.attr("class", `${className} active`);
circle.attr("cx", activeCX)
}
rect.on("click", (d) => {
if (rect.classed("active")) {
rect.attr("class", className)
.transition(t)
.attr("fill", initialFill);
circle.transition(t)
.attr("cx", cX);
} else {
rect.attr("class", `${className} active`)
.transition(t)
.attr("fill", activeFill);
circle.transition(t)
.attr("cx", activeCX);
}
});
}
drawToggleBtn();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment