Scrolls six-pack div to mouse position
HTML
<div id="parentElement">
<div id="first_child">first</div>
<div class="six-pack">1 of 6pack</div>
<div class="six-pack">2 of 6pack</div>
<div class="six-pack">3 of 6pack</div>
<div class="six-pack">4 of 6pack</div>
<div class="six-pack">5 of 6pack</div>
<div class="six-pack">6 of 6pack</div>
<div id="last_child">last</div>
</div>
CSS
#parentElement {
height: 80vh;
margin: 10vh auto;
width: 50vw;
border: 1px solid black;
font-size: x-large;
overflow-y: scroll;
position: relative;
}
#parentElement > div {
border: 1px solid black;
}
.six-pack {
text-align: center;
height: 50px;
line-height: 50px;
background-color: blanchedalmond;
}
#first_child, #last_child {
height: 70vh;
line-height: 70vh;
text-align: center;
font-weight: bold;
}
JavaScript
const parentElement = document.getElementById('parentElement'),
sixPackFirstElement = document.querySelector('#parentElement > div:nth-of-type(2)'),
sixPackLastElement = document.querySelector('#parentElement > div:nth-of-type(7)'),
sixPackTop = sixPackFirstElement.offsetTop,
sixPackBottom = sixPackLastElement.offsetTop + sixPackLastElement.offsetHeight,
// yScrollOffset = sixPackTop, // to attempt to position the top of the 6pack at the cursor
yScrollOffset = (sixPackTop + sixPackBottom)/2, // to attempt to position the center of the 6pack at the cursor
yScrollMin = sixPackBottom - parentElement.offsetHeight;
parentElement.addEventListener('mouseenter', (event) => {
const yScrollSixPackTop = yScrollOffset - event.offsetY;
// or, using event.clientY:
//const yScrollSixPackTop = yScrollOffset + parentElement.getBoundingClientRect().y - event.clientY;
parentElement.scrollTop = Math.min(Math.max(yScrollMin, yScrollSixPackTop), sixPackTop);
});