Scroll JS

by João Vitor Scheuermann

HTML

<div class="scrollTarget"></div>

<div id="scroll">
  <div id="bar" />
  <div id="handle" />
</div>

CSS

.scrollTarget {
  position: absolute;
  top:10px;
  width: 30px;
  height: 30px;
  background: blue;
}

#scroll {
  position: absolute;
  top: 200px;
  width: 500px;
  height: 5px;
}

#scroll #bar {
  position: absolute;
  width: 100%;
  height: 100%;
  background: red;
}

#scroll #handle {
  position: absolute;
  left: 0;
  width: 30px;
  height: 30px;
  top: calc((-30px/2) + (100%/2));
  background: blue;
}

JavaScript

/*setLayersContainerScroll(el, scalar) {
  let percent = (el.scrollHeight - el.getBoundingClientRect().height) / 100
  el.scrollTop = percent * scalar
}*/

function el(selector) {
  return document.querySelector(selector)
}

function property(el, propertyName) {
  return window.getComputedStyle(el)[propertyName]
}

function scrollX(barSelector, handleSelector, drag) {
  var bar = el(barSelector)
  var handle = el(handleSelector)

  var min = 0 + parseInt(property(handle, 'width')) * 0.8
  var max = parseInt(property(bar, 'width')) - parseInt(property(handle, 'width'))

  var x = 0
  var lastX = 0

  handle.addEventListener('mousedown', initDrag, false)

  function initDrag(e) {  	
  	x = e.layerX
    document.documentElement.addEventListener('mousemove', doDrag, false)
    document.documentElement.addEventListener('mouseup', stopDrag, false)
  }

  function doDrag(e) {
  	var left = parseInt(property(handle, 'left'))
    if (e.clientX < min) {
    	handle.style.left = 0 + 'px'
      left = parseInt(property(handle, 'left'))
      drag(0, 0)
      return
    }
    if (e.clientX - parseInt(property(handle, 'width')) * 0.6 > max) {
    	handle.style.left = max + 'px'
      left = parseInt(property(handle, 'left'))
      drag(max, 100)
      return
    }    
    handle.style.left = ((e.clientX - x)) + 'px'
    left = parseInt(property(handle, 'left'))
    drag(left, left > -1 ? Math.ceil((100 * left)/max) : 0)    
  }

  function stopDrag(e) {
    document.documentElement.removeEventListener('mousemove', doDrag, false)
    document.documentElement.removeEventListener('mouseup', stopDrag, false)
  }
}

var startX = parseInt(property(el('.scrollTarget'), 'left'))
scrollX('#bar', '#handle', function (left, percent) {
	el('.scrollTarget').style.left = startX + left + 'px'
})