themactep.com

A home of miscellaneous projects by Paul Philippov.

Notes

Webdev: How to scroll a list with mouse moves

<nav>
<ol>
<li><a href="">item 1</a></li>
<li><a href="">item 2</a></li>
<li><a href="">item 3</a></li>
<li><a href="">item 4</a></li>
...
<li><a href="">item n</a><li>
</ol>
</nav>
nav { height: 10rem; overflow: hidden; }
function getAbsoluteTop(el) {
  let top = el.offsetTop;
  if (el.offsetParent)
    top = top + getAbsoluteTop(el.offsetParent);
  return top;
}

function scrollNav(event) {
  const el1 = document.querySelector('nav');
  const el2 = document.querySelector('nav ol');
  const el3 = document.querySelector('nav ol li');
  const el1AbsTop = getAbsoluteTop(el1);
  const margin = el2.offsetTop - el1.offsetTop;
  const top = (event.pageY - el1AbsTop - margin - el3.clientHeight) /
    (el1.clientHeight - margin * 2 - el3.clientHeight * 2) *
    (el2.clientHeight - el1.clientHeight);
  document.querySelector('nav').scrollTo(0, top > 0 ? Math.round(top) : 0);
}
document.querySelector('nav').addEventListener('mousemove', scrollNav);

Demo