I'm looking for a pure JS script that can make a list of items scroll vertically but based on the users mouse position above them.
So, if you are hovered on the list but closer to the top, you will see the items near the top of the list and hover over near the bottom you will see the items nearer the end of the list.
I've seen this technique used several times but now I am trying to find an example I can't find one!
It basically allows more content to fit in a small space whilst still allowing access to it all.
Any ideas?
You can listen for the mousemove event on the element and get the y coordinate of the mouse relative to the element. Then, you can create an interval that scrolls up/down based on whether the relative y coordinate is greater than half the height of the elemet.
You'll also need to add a mouseleave event listener that clears the interval so it doesn't keep scrolling after the mouse is no longer hovering over the element.
const halfHeight = list.offsetHeight / 2;
var interval
list.addEventListener('mousemove', function(e) {
const relativeY = e.clientY - list.getBoundingClientRect().top;
clearInterval(interval)
interval = setInterval(() => list.scrollTop += relativeY > halfHeight ? 10 : -10, 100)
})
list.addEventListener('mouseleave', () => {
clearInterval(interval)
})
#list {
height: 150px;
overflow: auto;
border: 1px solid;
}
<div id="list"><ul><li>1<li>2<li>3<li>4<li>5<li>6<li>7<li>8<li>9<li>10<li>11<li>12<li>13<li>14<li>15<li>16<li>17<li>18<li>19<li>20</ul></div>