Reputation: 196
I'm using draggable from Jquery UI to do a drag effect, the difficulty is in calculating from 0 to 100, the position of the drag inside the bar. Here's what I've done:
$('.drag').draggable({
axis: 'x',
containment: 'parent',
drag: function() {
var largura = $('.bar').width();
var posicaoX = $(this).position().left;
posicaoX = (posicaoX*100)/largura;
var l = (100 * parseFloat($(this).position().left / parseFloat($(this).parent().width())));
$('#show').val(l);
}
});
.bar{
width: 150px;
height: 5px;
background: #000000;
position: relative;
margin-top: 20px;
margin-bottom: 20px;
}
.drag{
width: 20px;
height: 20px;
background: #d18f4f;
position: absolute;
top: -7px;
left: 0px;
cursor: pointer;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div class="bar">
<div class="drag"></div>
</div>
<input type="text" value="0" id="show">
The code seems to be right, I think I have to calculate the size of the drag and add or decrease the total, or something, can you help me?
Upvotes: 0
Views: 452
Reputation: 815
Since you're dealing with the left edge of the .drag element, you have to account for the width of that element, since draggable won't let the right side slide past the end of the .bar
So simply:
var l = (100 * parseFloat($(this).position().left / parseFloat($(this).parent().width()-20)));
or
var l = (100 * parseFloat($(this).position().left / parseFloat($(this).parent().width() - $(this).width()));
Upvotes: 3