Search code examples
javascripthtmlplayback-rate

How to reset an HTML range slider to default position and default playbackRate value with a single button press


I’m a total newbiew here, but trying my best to figure this out.

I can specify the video playback speed with a range slider no problem, but after changing the speed on the slider, instead of manually pushing it back to it’s original value I’d like to be able to push a “Reset speed” button and have the slider automatically reset both to it’s original position and original speed value of “1”. I’ve managed to get the slider to reset to it’s starting position but it still retains the altered playback speed value. Below is the code I came up with. Can anyone help me with this? Thank you!

<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function () {
 
  var v = document.getElementById("myVideo");
  var p = document.getElementById("pbr");
  var c = document.getElementById("currentPbr");
 
  p.addEventListener('input',function(){
    c.innerHTML = p.value;
    v.playbackRate = p.value;
  },false);

};
</script>

<script>
function myFunction(){
  document.getElementById("myForm").reset();
} 
  
function setPlaySpeednormal(){ 
  vid.playbackRate = 1;
}
</script>

 
<style>

.holder {
   width:640px;
   height:360;
   margin: 0 auto;
   margin-bottom:14em;
}
 
#pbr {
   width:50%;
}

</style>
 
</head>
<body>
 
<div class="holder">
<video id="myVideo" controls>
<source src="https://www.dropbox.com/s/5rjbtmantuow8vw/testvideo_hfd.mp4?raw=1" 
          type='video/mp4'/>
</video>
 
<form id= "myForm">
<input id="pbr" type="range" value="1" 
                    min="0.5" max="1.5" step="0.05" >
 
<p>Playback Rate <span id="currentPbr">1</span></p>
    
<input type="button" value="Reset speed" onclick="myFunction();setPlaySpeednormal();"/>
  
</form>
  
  
</div>


</body>
</html>

Solution

  • In the window.onload function, you've declared a variable with scope of only that function. You can't access it outside when you need it in the setPlaySpeednormal function. So, move the variable v outside:

    var v;
    window.onload = function () {
     
      v = document.getElementById("myVideo");
      var p = document.getElementById("pbr");
      var c = document.getElementById("currentPbr");
     
      p.addEventListener('input',function(){
        c.innerHTML = p.value;
        v.playbackRate = p.value;
      },false);
    
    };
    

    Also, in your setPlaySpeednormal function, you are using a variable named vid. Even though the variable you are using for video element is named v

    function setPlaySpeednormal(){ 
      v.playbackRate = 1; // change vid to v
    }