I answered a question earlier with similar functionality.
Accurate 3 event headsets:
- when the mouse is pressed
- when the mouse is dropped
- when the mouse is moved
Using var ativo
you can appreciate true
or false
with the mousedown
and mouseup
. This way the 3rd Event Controller will know whether to act or not when reading the first line if (!ativo) return;
Then you can use a logic if (position < limites.left || position > limites.right) return;
to prevent it from dragging out 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;
});
Using a different color for the selected part: http://jsfiddle.net/6s6wvk3f/2/
It worked, but I just wanted one more thing, when I moved the "side. ball", the side that has already passed in the case of the left side was of one color, and the right side that in case still has to go there, stay of another. Is there a way? Like this: http://prntscr.com/7wbm0e
– Paulo Cavalcante
Dude, I think I’m gonna try to implement this solution to my script instead of the
input range
in the problem I had days ago, as input range seems to vary your browser style.+ 1! =)– Chun
@Kloves following the idea of the other question I referred to could do like this: http://jsfiddle.net/6s6wvk3f/2/
– Sergio