javascripthtmldom-eventsjquery-ui-slider

Create Jquery UI Slider from scratch


I am new to Javascript and trying to create Jquery UI custom range slider on my own. Below is html and CSS code for this task.

#slider {
  position: relative;
  height: 15px;
  width: 400px;
  margin: 10px;
  border: 1px solid #c5c5c5;
}

.ui-slider {
  position: absolute;
  width: 20px;
  height: 20px;
  background-color: rgb(246, 246, 246);
  border: 1px solid #c5c5c5;
  left: 50%;
  top: -4.5px;
  border-radius: 3px;
}

.ui-slider:hover {
  background-color: rgb(237, 237, 237);
}
<div id="slider">
  <span class="ui-slider"></span>
</div>

Now I think some Javascript event should be attached to span element to make it slide back and forth. Should I use mouseDown or onDrag event listeners for this task? Please help me to write Javascript code to make this slider working actually. You can find slider that I want to build on this link.


Solution

  • var sliderSpan = document.getElementById("slider-span");
    var slider = document.getElementById("slider");
    
    sliderSpan.onmousedown = function(event) {
      var sliderCoords = getCoords(slider);
      var sliderSpanCoords = getCoords(sliderSpan);
      var shift = event.pageX - sliderSpanCoords.left;
    
      document.onmousemove = function(event) {
        var left =
          ((event.pageX - shift - sliderCoords.left) / sliderCoords.width) * 100;
        if (left < 0) left = 0;
        if (left > 100) left = 100;
        sliderSpan.style.left = left + "%";
      };
      document.onmouseup = function() {
        document.onmousemove = document.onmouseup = null;
      };
      return false;
    };
    
    function getCoords(elem) {
      var box = elem.getBoundingClientRect();
      return {
        top: box.top + pageYOffset,
        left: box.left + pageXOffset,
        width: box.right - box.left
      };
    }
    #slider {
      position: relative;
      height: 15px;
      width: 400px;
      margin: 10px;
      border: 1px solid #c5c5c5;
    }
    
    .ui-slider {
      position: absolute;
      width: 20px;
      height: 20px;
      background-color: rgb(246, 246, 246);
      border: 1px solid #c5c5c5;
      left: 0%;
      top: -4.5px;
      border-radius: 3px;
      margin-left: -10px;
    }
    
    .ui-slider:hover {
      background-color: rgb(237, 237, 237);
    }
    <div id="slider">
      <span class="ui-slider" id="slider-span"></span>
    </div>