Video Volume Slider in HTML5 and JavaScript
Instead of checking whether the volume control has changed every millisecond (highly inefficient), you should create an event listener that will fire only when your volume control changes. Here is an example:
var video = document.getElementById('video');
var volumeControl = document.getElementById('vol-control');
volumeControl.addEventListener('change',function(){
video.volume = this.value / 100;
});
UPDATE (with oninput
event listener)
var video = document.getElementById('video');
var volumeControl = document.getElementById('vol-control');
var setVolume = function(){
video.volume = this.value / 100;
};
volumeControl.addEventListener('change',setVolume);
volumeControl.addEventListener('input',setVolume);
It's actually best to handle both the "input" and "change" event so that the volume updates in real-time with the slider with all newer browsers ("change" is only supposed to happen when the user releases the mouse button, even though it apparently works in Chrome, and IE10 requires you to handle "change" instead of "input"). Here's a working example:
<video id="video" autoplay>
<source src="/720p.mp4" type="video/mp4">
</video>
<input id="vol-control" type="range" min="0" max="100" step="1" oninput="SetVolume(this.value)" onchange="SetVolume(this.value)"></input>
<script>
function SetVolume(val)
{
var player = document.getElementById('video');
console.log('Before: ' + player.volume);
player.volume = val / 100;
console.log('After: ' + player.volume);
}
</script>
...here's a live demo: https://jsfiddle.net/2rx2f8dh/