JSFiddle - React, Tailwind, and code Playground
by radu
HTML
<div id="wrapper">
<div id="pan-track">
<div id="handle"></div>
</div>
<div id="browser" class="grab">
<div id="panner"></div>
<div id="content"></div>
</div>
</div>
CSS
#wrapper
{
margin:80px auto;
width:60em;
}
#pan-track
{
border:1px solid gray;
height:15px;
position:relative;
}
#handle
{
background-color:blue;
cursor:move;
height:15px;
position:absolute;
-webkit-user-select:none;
width:15px;
}
#browser
{
background-image:url("/img/browser-bg.png");
border:1px solid gray;
/* Chrome 11 does not support switching cursor after drag event */
height:60px;
margin:0px auto;
padding-bottom:20px;
overflow-x:scroll;
position:relative;
text-align:top;
-webkit-user-select:none;
}
#panner
{
background-color:blue;
opacity:0.5;
height:100%;
left:0px;
position:absolute;
width:60px;
z-index:1;
}
#content
{
height:1px;
width:3200px;
}
JavaScript
// Movement of handle and panner
var handleMouse = false,
autoScroll = false,
scrollInterval;
$('#handle').mousedown(function() {
handleMouse = true;
})
$('body').mousemove(function(e) {
if (handleMouse) {
$('body').css('-webkit-user-select', 'none');
var pos = e.clientX - $('#wrapper').position().left;
var currentLeft = parseInt($('#panner').css('left'), 10);
// be careful with scrollWidth
var maxLeft = $('#browser')[0].scrollWidth - $('#panner').width();
var scrollLeft = $('#browser').scrollLeft();
// set new position as long as it's not out of bounds
if (pos + scrollLeft >= 0 && pos + scrollLeft <= maxLeft) {
if (!autoScroll) {
$('#handle').css('left', pos);
$('#panner').css('left', pos + $('#browser').scrollLeft());
}
//console.log(e.clientX >= $('#browser').width() - $('#panner').width());
if (e.clientX <= $('#wrapper').position().left || e.clientX >= $('#browser').width() + 351 - $('#panner').width()) {
// if cursor is outside of bounds scroll until action is cancelled
// make sure autoscroll only gets tripped once
var direction = '',
stepSize = 25,
scrollDelay = 40;
if (e.clientX <= $('#wrapper').position().left) {
direction = 'left';
} else {
direction = 'right';
}
if (!autoScroll) {
autoScroll = true;
scrollInterval = setInterval(doScroll, scrollDelay, direction, stepSize, $('#browser')[0].scrollWidth - $('#panner').width());
}
} else {
// also cancel scroll if cursor moves back in bounds
if (autoScroll) {
autoScroll = false;
clearInterval(scrollInterval);
...