I want to create a range like you see in the picture below:
Here is my code for this:
<div >
<label for="distance" >Aranılan lokasyona uzaklık</label>
<div >
<output>40 </output>
<span>km uzaklık</span>
</div>
<input type="range" value="40" min="1" max="50" oninput="this.nextElementSibling.value = this.value" id="distance">
<div >50</div>
</div>
So what I am trying to achieve, I want to move this with the range input.
PS: I am using bootstrap for range.
CodePudding user response:
If the solution I developed below is used, it is necessary to develop a transform function to evaluate the new position of the text. The following equation generates the margin value for the new position according to the change amount. For example;
T(x) = x * 4 60;
If there isn't an easier method, the transform function should also take the page width as input:
T(x, width)
let output = document.getElementById('result');
let distance = document.getElementById('distance');
function changeValue(value){
output.innerHTML = `${50 - parseInt(value)}`;
/* If this method is used, it is necessary to develop a transformation method. */
let result = parseInt(value) * 4 60;
distance.style.marginLeft = `${result}px`;
}
changeValue(40);
input{
margin-left: 100px;
}
#distance{
width: 200px;
}
<div >
<label for="distance" >Aranılan lokasyona uzaklık</label>
<div id="distance">
<output id="result">40</output>
<span> km uzaklık</span>
</div>
<input onchange="changeValue(this.value)" type="range" value="40" min="0" max="50" oninput="this.nextElementSibling.value = this.value" id="distance">
<div >Total: 50</div>
</div>
CodePudding user response:
Good old native JS... what a breeze!
First, check out the code snippet below
Now - let's break the solution down
CSS - The styling properties allow the ,moving label to have its own width able it to move around (as required)
JS - Register an event (I've used the mouse up event but you can use on change event or any other to suit your requirements). Then, make a simple calculation - how much progress have we done, project it to the actual input size. The only thing left is to adjust the new position to your label
Hope this help you to get things started
ENJOY
function x(input) {
const percent = input.value / 50
const position = percent * input.clientWidth
const labelElement = document.querySelector('.distance')
labelElement.style.left = `${position - labelElement.clientWidth / 2}px`
}
.distance {
display: inline-block;
position: relative;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div >
<label for="distance" >Aranılan lokasyona uzaklık</label>
<br/>
<div >
<output>40 </output>
<span>km uzaklık</span>
</div>
<input onm ouseUp=x(this) type="range" value="40" min="1" max="50" oninput="this.nextElementSibling.value = this.value" id="distance">
<div >50</div>
</div>

