Search code examples
javascriptslidervolume

Why is my vertical volume bar not working?


I'm trying to make a vertical slider that controls the volume of an audio i have on the background, it should be working but i have two problems: one is that for some reason it doesn't follow the mouse position, the other one is a big issue with dragging. The first drag doesn't show, but once I drag again it doesn't stop when releasing the mouse, and i can't click on the rest of the content in my page. Can anyone please help me figure this out? I'm still a beginner with Javascript. Thanks in advance!

var e = document.querySelector('.volume-slider-con');
var eInner = document.querySelector('.volume-slider');
var audio = document.querySelector('audio');
var drag = false;
e.addEventListener('mouseup',function(ev){
   drag = true;
   updateBar(ev.clientY);
});
document.addEventListener('mousemove',function(ev){
   if(drag){
      updateBar(ev.clientY); 
   }
});
document.addEventListener('mousdown',function(ev){
 drag = false; 
});
var updateBar = function (y, vol) {
   var volume = e;
        var percentage;
        if (vol) {
            percentage = vol * 100;
        } else {
            var position = y - volume.offsetTop;
            percentage = 100 - (25 * position / volume.clientHeight);
        }

        if (percentage > 100) {
            percentage = 100;
        }
        if (percentage < 0) {
            percentage = 0;
        }

        eInner.style.width = percentage +'%';
        audio.volume = percentage / 100;
};
.volume-slider-con{
  height:15px;
  width:10%;
    margin-top: 255px;
    margin-left: 106px;
     position:relative;
  background-color: #000000;
    transform: rotate(270deg);
    border-radius: 2px;
}
.volume-slider{
   height:100%;
   width:100%;
   position:relative;
   background-color: #ffffff;
    border-radius: 2px;
}
<div class="volume-slider-con">
<div class="volume-slider"></div>
</div>


Solution

  • You may consider using <input type="range"> and rotate it 90 degrees with css transform, instead of building one completely from scratch.

    You can then as well use event listeners to perform actions on input and on change.

    On input event runs as long as the slider thumb slides over the range (while dragging) and returns the value of the position of the slider continuously. On change event runs only once as soon as the slider gets released.