JSFiddle - React, Tailwind, and code Playground
by Nabaraj Saha
HTML
<label for="vol">Volume (between 0 and 50):</label>
<input type="range" id="vol" name="vol" min="0" max="50" oninput="showVal(this.value)" onchange="showVal(this.value)">
<div class="showVal"></div>
<div id="js-slider">
<div class="slideTrack"></div>
<span id="sl" class="handle slideLeft"></span>
<span id="rl" class="handle slideRight"></span>
</div>
CSS
#js-slider {
width: 100%;
height: 10px;
border: 1px solid #c5c5c5;
border-radius: 5px;
position: relative;
}
.handle {
border: 1px solid #c5c5c5;
background-color: #f6f6f6;
display: block;
position: absolute;
z-index: 2;
width: 1.2em;
height: 1.2em;
cursor: default;
-ms-touch-action: none;
touch-action: none;
top: 50%;
transform: translateY(-50%);
border-radius: 3px;
}
.slideLeft{
left:30%;
}
.slideRight{
left:50%;
}
JavaScript
function showVal(val){
console.log(val);
document.querySelectorAll(".showVal")[0].innerHTML = val;
}
dragElement(document.getElementById("js-slider"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0, slide;
/* if (document.getElementById(elmnt.id + "header")) {
// if present, the header is where you move the DIV from:
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
// otherwise, move the DIV from anywhere inside the DIV:
elmnt.onmousedown = dragMouseDown;
} */
let handles = elmnt.querySelectorAll(".handle");
for (const handle of handles) {
handle.onmousedown = dragMouseDown
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
console.log(e);
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
console.log(e.clientX);
if(e.target.classList.contains("handle")){
slide = e.target;
}
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
/* e.target.style.top = (e.target.offsetTop - pos2) + "px" */;
/* slide.style.left = (e.target.offsetLeft - pos1) + "px" */;
slide.style.left = e.clientX;
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}