Skip to content

Instantly share code, notes, and snippets.

@noblemillie
Last active July 2, 2018 15:45
Show Gist options
  • Save noblemillie/fb03d0374ee70255555d2dfc0adfbceb to your computer and use it in GitHub Desktop.
Save noblemillie/fb03d0374ee70255555d2dfc0adfbceb to your computer and use it in GitHub Desktop.
Chart Slider
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font-family: sans-serif;
background-color: #c2e5a8;
}
.slider rect {
fill: gray;
shape-rendering: crispEdges;
}
.slider line {
fill: none;
stroke: black;
stroke-width: 3px;
opacity: 0.3;
padding-top: 0px;
shape-rendering: crispEdges;
}
/* #line2 {
fill: none;
stroke: red;
stroke-width: 2px;
opacity: 0.3;
padding-top: 0px;
shape-rendering: crispEdges;
} */
#header {
color: red;
opacity: 0.5;
font-size: 30px;
margin: -36px 520px 0px 50px;
}
</style>
<body>
<div id="chart"></div>
<h3 id="header"></h3>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript">
function translate(x, y) {
return 'translate(' + x + ',' + y + ')';
}
var margin = { top: 50, right: 20, bottom: 0, left: 20},
width = 720 - margin.left - margin.right,
height = 221 - margin.top - margin.bottom,
svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("color", "purple")
.append('g')
.attr('transform', translate(margin.left + 32, margin.top + 85));
var minDate = new Date(2018, 7, 1, 4),
scale = d3.scaleTime()
.domain([minDate, d3.timeHour.offset(minDate, 6)])
.range([-23, width])
.clamp(true),
format = d3.timeFormat('%-I:%M %p');
// axis
svg.append('g')
.attr('class', 'axis')
.call(d3.axisBottom(scale).ticks(d3.timeMinute.every(60)));
var slider = svg.append('g')
.attr("class", "slider")
.call(d3.drag().on('drag', dragged));
var rectWidth = 8;
var rect = slider.append("rect")
.attr("x", -rectWidth / 2 - 30)
.attr("y", -20)
.attr("width", rectWidth + 20)
.attr("height", 50)
.attr("stroke", "red")
.attr("stroke-width", "3px")
.attr("opacity", 0.3)
var line = slider.append("line")
.attr('y2', height)
.attr('x2', 0)
.attr('stroke-dasharray', '1,1')
.attr('transform', translate(margin.left - 40, margin.top - 70))
// var line2 = slider.append("line")
// .attr("class", "line2")
// .attr('y2', height - 40)
// .attr('x2', 130)
// // .attr('stroke-width', '1px')
// .attr('stroke-dasharray', '4,2')
// .attr('transform', translate(margin.left - 40, margin.top - 10))
function updateHeader(date) {
d3.select('#header').text('at the stroke of ' + format(date) + ", you go hard in the paint")
}
function dragged(d) {
var x = Math.min(Math.max(d3.event.x, 44), width);
value = scale.invert(x);
d3.select('.slider').attr('transform', translate(x, -30));
updateHeader(value);
}
updateHeader(minDate);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment