I want my slider to move only on those possible values, currently, it is possible to place the slider on 60, and in this case it should be 50. I just want to get possible values between 0, 30, 50, and 90.
how can do it?
const inputRange = document.getElementById('inputRange');
inputRange.addEventListener('input', function() {
const valor = inputRange.value;
textSlider=document.getElementById("textRange");
textSlider.style.left= valor+"%";
textSlider.innerText= valor + "%";
});
.rangeWrap{
border:1px solid red;
display: inline-block;
position:relative;
}
#textRange{
display:block;
position:absolute;
left:0px;
bottom:0px;
pointer-events: none;
font-size: 14px;
line-height: 1;
text-shadow: none;
padding: 3px 5px;
background-color: #006cfa;
color: white;
border-radius: 4px;
}
#textRange:after{
content:"";
position: absolute;
right: 50%;
top: -4px;
width: 0;
height: 0;
border-style: solid;
border-width: 0 4px 4px 4px;
border-color: transparent transparent #006cfa transparent;
z-index:9998;
}
<section class="rangeWrap">
<input type="range" id="inputRange" value="0" min="0" max="90" step="30" list="ticks" />
<datalist id="ticks">
<option value="0" label="0%"></option>
<option value="30" label="30%"></option>
<option value="50" label="50%"></option>
<option value="90" label="90%"></option>
</datalist>
<span id="textRange" >0%</span>
</section>
2
Answers
I have inserted the code to dynamically detect which tick is closer to the user’s dragged/current value. I have added comments to explain what I did. Also I removed the
step
property on input to enable dynamic closest tick value detection.My solution was to just snap the result to one of the allowed values, which is stored in the const
allowed
. Then you just loop over them in an onchange function and find the nearest one and set the input’s value.