JSFiddle - React, Tailwind, and code Playground
by arcm111
HTML
<body>
<div id="parent">
<div id="mask">
<div id="cont"></div>
<div id="scrollBarCont"><div id="scrollBar"></div></div>
</div>
</div>
</body>
CSS
body,html {
width: 100%;
height: 100%;
margin: 0;
padding: 0
}
#parent {
background: red;
padding: 10px;
}
#mask {
position: relative;
overflow: hidden;
height: 300px;
width: 100%;
background: blue;
}
#cont {
position: absolute;
top: 0;
left: 0;
background: green;
width: 100%;
padding-right: 10px;
}
#scrollBarCont{
position: absolute;
top: 0;
right: 0;
width: 10px;
height: 100%;
background: purple;
}
#scrollBar {
width: 10px;
position: absolute;
top: 0;
left: 0;
background: yellow
}
JavaScript
function enableScroll(elm, parent, cont, marg)
{
var pos, ph = parent.offsetHeight, ch = cont.offsetHeight, elmY, contY;
var scale = ch / (ph - (2 * marg));
var bh = ph / scale;
elm.style.height = bh + 'px';
elm.style.top = marg + 'px';
var update = function()
{
elmY = elm.offsetTop;
contY = cont.offsetTop;
ph = parent.offsetHeight;
ch = cont.offsetHeight;
scale = ch / (ph - (2 * marg));
bh = ph / scale;
if (ch <= ph) cont.style.top = 0;
elm.style.height = bh + 'px';
elm.style.top = -contY / scale + marg + 'px';
elm.style.display = (ch <= ph) ? 'none' : 'block';
};
var scrollToEnd = function()
{
if (ch > ph)
{
elm.style.top = ph - bh - marg + 'px';
cont.style.top = ph - ch + 'px';
}
};
elm.data = {'update': update, 'scrollToEnd': scrollToEnd};
var onMove = function(event)
{
var e = (event) ? event : window.event, dist = e.pageY - pos;
if(elmY + dist < marg)
{
elm.style.top = marg + 'px';
cont.style.top = 0;
}
else if(elmY + dist + bh > ph - marg)
{
elm.style.top = ph - bh - marg + 'px';
cont.style.top = ph - ch + 'px';
}
else
{
elm.style.top = elmY + dist + 'px';
cont.style.top = contY - scale * dist + 'px';
}
};
var onUp = function()
{
document.removeEventListener('mousemove', onMove, false);
document.removeEventListener('mouseup', onUp, false);
};
elm.onmousedown = function(event)
{
var e = (event) ? event : window.event, y = e.pageY;
e.preventDefault();
pos = y;
update();
if (elm.offsetHeight != bh) elm.style.height = bh + 'px';
document.addEventListener('mousemove', onMove, false);
document.addEventListener('mouseup', onUp,...