Drag div into another

2

I wanted to do a volume controller, I already did css, php, html, but js and jquery are missing to finish. I wanted the ball to drag inside the .controlar

CSS:

.bola {
width: 10px;
height: 10px;
}
.controlar {
width: 100px;
height: 10px;
}

HTML:

<div class="controlar"><div class="bola"></div></div>
    
asked by anonymous 23.07.2015 / 23:43

1 answer

2

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

    
23.07.2015 / 23:53