Using draggable error when calculating the percentage

Asked

Viewed 12 times

0

I’m using draggable from Jquery UI to do a drag effect (drag), the difficulty is in calculating, from 0 to 100, the drag position within the bar. Look what I’ve done:

$('.drag').draggable({
	axis: 'x',
	containment: 'parent',
	drag: function() {
		var largura = $('.barra').width();
		var posicaoX = $(this).position().left;
		posicaoX = (posicaoX*100)/largura;
		var l = (100 * parseFloat($(this).position().left / parseFloat($(this).parent().width())));
		$('#mostra').val(l);
	}
});
.barra{
  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="barra">
  <div class="drag"></div>
</div>
<input type="text" value="0" id="mostra">

The code is apparently right, I believe I have to calculate the drag size and add or decrease the total or something, can help me?

  • It won’t reach 100 ever because it’s based on the left edge of the square, and that edge will never touch the end of the bar.

1 answer

1

As @Sam said you have to discount the width of the button, I set an example with the correction.

    $('.drag').draggable({
		axis: 'x',
		containment: 'parent',
		drag: function() {
			var largura = ($('.barra').width()) - 20;
			var posicaoX = $(this).position().left;
			var valor = (posicaoX * 100) / largura;
			$('#mostra').val(valor);
		}
	});
	.barra{
		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="barra">
	<div class="drag"></div>
</div>
<input type="text" value="0" id="mostra">

Browser other questions tagged

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