D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
mforando
Full window
Github gist
JavaScript Horizontal Scroll + Drag
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } /* width */ ::-webkit-scrollbar { width: 8px; height:8px; } /* Track */ ::-webkit-scrollbar-track { box-shadow: inset 0 0 3px rgb(145,145,145); border-radius: 10px; } /* Handle */ ::-webkit-scrollbar-thumb { background: rgb(0,130,101); border:1px solid black; border-radius: 10px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #b30000; } #container { height:auto; padding-bottom:5px; width:800px; display:block; overflow-x:scroll; overflow-y:hidden; white-space: nowrap; } #controls { height:25px; margin-top:10px; margin-left:10px; } select{ width:300px; } .indicatorDivs{ display:table; cursor: grab; } </style> </head> <body> <div id="controls"> </div> <div id="container"> </div> <script> var indicators = ["a","b","c","d","e","f","g","h","i"] d3.select("#container") .call(d3.zoom().scaleExtent([0,1]) .interpolate(d3.interpolateLinear) .on("zoom", zoomed)) var divs = d3.select("#container").selectAll(".indicatorDivs").data(indicators) divs.enter() .append("div") .attr("class","indicatorDivs") .style("display","inline-block") .style("width", 150 + "px") .style("height", 150 + "px") .style("border","1px solid black") .call(d3.drag().on("start", dragstarted) .on("drag", dragged) .on("end", dragended)); var headers =d3.selectAll(".indicatorDivs").selectAll(".headers").data(function(d){return [d]}) headers.enter() .append("h2") .attr("class","headers") .style("color","black") .style("margin-left","20px") .text(function(d){return d}) var x0 = 0 var x1 = 0 var deltax = 0 var scroll0 = 0; var maxScroll = d3.select("#container").node().scrollWidth function dragstarted(){ //get initial x position x0 = d3.event.x scroll0 = d3.select("#container").node().scrollLeft } function dragged(d) { //calculate change in x, and the associated change in scrolling x1 = d3.event.x deltax = x1-x0; //move scroller to starting scroll value + change in x //the Math.min is probably unneccesary since it will automatically //stop the scroller at the end of the div d3.select("#container").property("scrollLeft",Math.min(scroll0 + deltax,maxScroll)) } function dragended(d) { d3.select(this).classed("active", false); } function zoomed(){ // console.log(d3.event) d3.select("#container").property("scrollLeft",maxScroll*(1-d3.event.transform.k)) } </script> </body>
https://d3js.org/d3.v4.min.js