title: Making JavaScript Custom ScrollBar
body: <p>I said <strong>&#8220;JavaScript&#8221;</strong>. I'm trying to make my own JavaScript custom scrollbar. It's almost successful. The problem is that I can't get an accurate multiplier for the scrolling speed. This is my code:</p>
  
  <pre><code>var elem = document.getElementById('scroll-area'),
      track = elem.children[1],
      thumb = track.children[0],
      height = parseInt(elem.offsetHeight, 10),
      cntHeight = parseInt(elem.children[0].offsetHeight, 10),
      trcHeight = parseInt(track.offsetHeight, 10),
      distance = cntHeight - height,
      mean = 50, // For multiplier (go faster or slower)
      current = 0;
  
  elem.children[0].style.top = current + "px"; // Set default `top` value as `0` for initiation
  thumb.style.height = Math.round(trcHeight * height / cntHeight) + 'px'; // Set the scrollbar thumb hight
  
  var doScroll = function (e) {
  
      // cross-browser wheel delta
      e = window.event || e;
      var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
  
      // (1 = scroll-up, -1 = scroll-down)
      // Always check the scroll distance, make sure that the scroll distance value will not
      // increased more than the content height and/or less than zero
      if ((delta == -1 &amp;&amp; current * mean &gt;= -distance) || (delta == 1 &amp;&amp; current * mean &lt; 0)) {
          current = current + delta;
      }
  
      // Move element up or down by updating the `top` value
      elem.children[0].style.top = (current * mean) + 'px';
      thumb.style.top = 0 - Math.round(trcHeight * (current * mean) / cntHeight) + 'px';
  
      e.preventDefault();
  
  };
  
  if (elem.addEventListener) {
      elem.addEventListener("mousewheel", doScroll, false);
      elem.addEventListener("DOMMouseScroll", doScroll, false);
  } else {
      elem.attachEvent("onmousewheel", doScroll);
  }
  </code></pre>
  
  <p>And the markup:</p>
  
  <pre><code>&lt;div id="scroll-area"&gt;
      &lt;div&gt;&lt;!-- CONTENT --&gt;&lt;/div&gt;
      &lt;span class="scrollbar-track"&gt;&lt;span class="scrollbar-thumb"&gt;&lt;/span&gt;&lt;/span&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>My problem is on <code>mean = 50</code>. When you scroll the container until the bottom of content, the red line that I made in the demo page should stop right at the bottom of the container, not higher than  that.</p>
  
  <p>Anyone have an idea for the accurate result?</p>
  
  <p><strong>PS:</strong> I also want to add a function that will enable user to scroll the content by dragging the scrollbar thumb. But I think I want to focus on this issue first. Thanks for your help.</p>
  
  <p><strong>DEMO:</strong> <a href="http://jsfiddle.net/tovic/2B8Ye/" rel="nofollow">http://jsfiddle.net/tovic/2B8Ye/</a></p>