How can I insert an tracker inside input range? Here is my code =>
const marker = document.createElement('div'); marker.classList.add('range-marker'); const range = document.getElementById('range'); range.appendChild(marker); range.addEventListener('input', () => { const percent = (range.value - range.min) / (range.max - range.min); const pixels = percent * range.offsetWidth; marker.style.left = `${pixels}px`; });
.range-marker { position: absolute; top: -5px; width: 100px; height: 10px; border-radius: 50%; background-color: red; z-index: 100; }
<input type="range" id="range">
I don’t know how but isn’t working. There are no errors… can you please help me fixing it?
Thank you.
Advertisement
Answer
You bascially need to put the input and the range marker inside a wrapper and use absolute position on range marker to position the red tracker. This can be implemented like below. Please note the appending div will go inside the wrapper and not the input.
const marker = document.createElement('div'); marker.classList.add('range-marker'); const range = document.getElementById('container'); range.appendChild(marker); range.addEventListener('input', () => { const percent = (range.value - range.min) / (range.max - range.min); const pixels = percent * range.offsetWidth; marker.style.left = `${pixels}px`; });
.range-marker { position: absolute; top: 2px; left:60%; width: 20px; height: 20px; border-radius: 50%; background-color: red; z-index: 100; } #container{ position:relative; display:inline-block }
<div id="container"> <input type="range" id="range"> </div>