I replied to a little question with similar functionality.
You need 3 event sinks:
- when the mouse is pressed
- when the mouse is released
- when the mouse is moved
Using var ativo
you can give true
or false
value with mousedown
and mouseup
. In this way, the 3rd event listener will know whether to act or not when reading the first line if (!ativo) return;
Then you can use if (position < limites.left || position > limites.right) return;
logic to prevent it from dragging out of the ends of .controlador
.
Example:
var slider = document.querySelector('.controlar .bola');
var limites = document.querySelector('.controlar').getBoundingClientRect();
var valor = document.getElementById('valor');
// arrastar slider
var ativo = false;
var offset = 0;
function toggleAtivo(e) {
if (e.target != slider) return;
ativo = (e.type == 'mousedown');
var sliderPosition = slider.getBoundingClientRect().left;
offset = sliderPosition - e.pageX;
}
window.addEventListener('mousedown', toggleAtivo);
window.addEventListener('mouseup', toggleAtivo);
window.addEventListener('mousemove', function (e) {
if (!ativo) return;
var position = e.pageX + offset;
if (position < limites.left || position > limites.right) return;
slider.style.left = position + 'px';
valor.innerHTML = position * limites.width / 100;
});
jsFiddle: link
Using a different color for the part already selected: link