Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a pure javascript range slider control

Tags:

javascript

I managed to create a somewhat working slider control but something feels kind of off. It doesnt quite behave as a normal control should. Sometimes while sliding it gets stuck and well, you might want to see for yourself.

How would you create the slider so that it slides smoothly without interruption or the user needing the cursor exactly on the red track?

function createRange(e) {
    var range = (((e.offsetX - 0) * (255 - 0)) / (200-40 - 0)) + 0;
  var rounded = Math.round(range);

  return rounded;
}

function colorSlider(e) {
    createRange(e)
}

var dragging = false;

document.getElementById("knob").addEventListener('mousedown', function(e) {
    dragging = true;
  e.target.style.pointerEvents = "none"
})

window.addEventListener('mousemove', function(e) {
  if (dragging) {
    if (createRange(e) <= 255) {
      document.getElementById("knob").style.left =  e.offsetX + "px"
    }
  }
})
like image 321
Asperger Avatar asked Mar 11 '23 11:03

Asperger


1 Answers

Here is a fixed version of your slider.

var dragging = false;
var knobOffset = 0;

var track = document.getElementById('track'),
    knob = document.getElementById('knob'),

    trackWidth = track.offsetWidth,
    trackLeft = track.offsetLeft,
    trackRight = trackLeft + trackWidth,

    knobWidth = knob.offsetWidth,
    maxRight = trackWidth - knobWidth; // relatively to track

knob.addEventListener('mousedown', function(e) {
    // knob offset relatively to track
    knobOffset = e.clientX - knob.offsetLeft;
    dragging = true;
});

window.addEventListener('mouseup', function(e) {
    dragging = false;
})

window.addEventListener('mousemove', function(e) {
  if (dragging) {
      // current knob offset, relative to track
      var offset = e.clientX - trackLeft - knobOffset;
      if(offset < 0) {
        var offset = 0;
      } else if(offset > maxRight) {
        var offset = maxRight;
      }
        
      knob.style.left = offset + "px"
  }
});
#track {width: 200px;height: 5px; margin:100px; background: red}
#knob {height: 10px; width: 40px; background: black;position: relative; }
<div id='track'>
  <div id="knob"></div>
</div>
like image 88
Bobo Avatar answered Mar 20 '23 10:03

Bobo