Skip to content

Instantly share code, notes, and snippets.

@shancarter
Last active November 28, 2016 00:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save shancarter/5979700 to your computer and use it in GitHub Desktop.
Save shancarter/5979700 to your computer and use it in GitHub Desktop.
A Simple HTML Slider With D3

DESCRIPTION

A simple d3.js slider

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.slider {
position: relative;
top: 40px;
left: 40px;
}
.slider-tray {
position: absolute;
width: 100%;
height: 6px;
border: solid 1px #ccc;
border-top-color: #aaa;
border-radius: 4px;
background-color: #f0f0f0;
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.08);
}
.slider-handle {
position: absolute;
top: 3px;
}
.slider-handle-icon {
width: 14px;
height: 14px;
border: solid 1px #aaa;
position: absolute;
border-radius: 10px;
background-color: #fff;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
top: -7px;
left: -7px;
}
</style>
<body>
<div class="slider"></div>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var width = 500;
var x = d3.scale.linear()
.domain([1, 100])
.range([0, width])
.clamp(true);
var dispatch = d3.dispatch("sliderChange");
var slider = d3.select(".slider")
.style("width", width + "px");
var sliderTray = slider.append("div")
.attr("class", "slider-tray");
var sliderHandle = slider.append("div")
.attr("class", "slider-handle");
sliderHandle.append("div")
.attr("class", "slider-handle-icon")
slider.call(d3.behavior.drag()
.on("dragstart", function() {
dispatch.sliderChange(x.invert(d3.mouse(sliderTray.node())[0]));
d3.event.sourceEvent.preventDefault();
})
.on("drag", function() {
dispatch.sliderChange(x.invert(d3.mouse(sliderTray.node())[0]));
}));
dispatch.on("sliderChange.slider", function(value) {
sliderHandle.style("left", x(value) + "px")
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment