javascript – improving volume slider with HTML and JS-ThrowExceptions

Exception or error:

I’ve created an simple audio slider (thanks to alot of the answers on here) that auto plays some audio (at zero volume) when the user clicks the slider, and then allows them to increase the volume if they wish.

My only issue is that instead of being a steady increase in volume as the user drags the slider, it only adjusts the volume when they release the slider with the mouse. Is there anyway i can achieve a constant volume adjustment with just the movement of the slider itself. Any help would be much appreciated

JS

var mediaClip;
var volume1;

function init()
{
    mediaClip = document.getElementById("mediaClip");
    volume1 = document.getElementById("volume1");

    mediaClip.play();
}

function setVolume() {
    var mediaClip = document.getElementById("mediaClip");
    mediaClip.volume = document.getElementById("volume1").value;
}


function play() {
    var audio = document.getElementById("mediaClip");
    audio.play();
}

HTML

<body onload="init()">
    <audio id="mediaClip" src="A Very Brady Special.mp3"  style="display:none" allow="autoplay" controls>
        <p>Your browser does not support the audio element</p>
    </audio>

    <input type="range" onchange="setVolume()" id='volume1' min=0 max=1 step=0.01 value='0' onclick="play()">
</body>
How to solve:

Simply use

<input type="range" oninput="setVolume()" id='volume1' min=0 max=1 step=0.01 value='0' onclick="play()">

instead of

<input type="range" onchange="setVolume()" id='volume1' min=0 max=1 step=0.01 value='0' onclick="play()">

###

Like connexo noted, use oninput instead of onchange, and I’d use setVolume(this) so you can apply it to any slider (and it’s neater).

var mediaClip;
var volume1;

function init() {
  mediaClip = document.getElementById("mediaClip");
  volume1 = document.getElementById("volume1");

  mediaClip.play();
}

function setVolume(el) {
  var newVal = el.value;
  
  document.getElementById("volumeVal").innerHTML = newVal;
  mediaClip.volume = newVal;
}


function play() {
  var audio = document.getElementById("mediaClip");
  audio.play();
}
<body onload="init()">

  <audio id="mediaClip" src="A Very Brady Special.mp3" style="display:none" allow="autoplay" controls>
    <p>Your browser does not support the audio element</p>
  </audio>

  <p>onChange</p>
  <input type="range" onchange="setVolume(this)" id='volume1' min=0 max=1 step=0.01 value='0' onclick="play()">
  
  <p>onInput</p>
  <input type="range" oninput="setVolume(this)" id='volume1' min=0 max=1 step=0.01 value='0' onclick="play()">
  
  <h3>Volume: <span id="volumeVal">0</span></h3>

</body>

Leave a Reply

Your email address will not be published. Required fields are marked *