Drag div inside another

Asked

Viewed 499 times

2

I wanted to make a volume controller, I’ve done css, php, html, but it lacks js and jquery to finish. I wanted to . ball dragged inside the . control

CSS:

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

HTML:

<div class="controlar"><div class="bola"></div></div>

1 answer

2


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;
});

jsFiddle: http://jsfiddle.net/2osvj77q/

Using a different color for the selected part: http://jsfiddle.net/6s6wvk3f/2/

  • 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

  • 1

    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! =)

  • @Kloves following the idea of the other question I referred to could do like this: http://jsfiddle.net/6s6wvk3f/2/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.