I have this volume slider:
<input id="volume-slider" type="range" min="0" max="1" step="0.1" value="0.5"></input>
$("#volume-slider").on("change", function() {
audio.volume = this.value;
if (audio.volume === 0) {
[... change class to make mute volume icon appear ...]
} else {
[... change class to make mute volume icon disappear ...]
}
});
This code is working fine. When the slider goes to 0, the mute speaker icon appears.
However, I want also the opposite.
I can make something like:
$("#speaker-button").on("click", function() {
audio.volume > 0 ? audio.volume = 0 : audio.volume = 0.5;
}
which works fine. However when I mute the volume setting audio.volume
to 0
it does not move the input range slider. If I mute the volume using the mute button, I want the range slider to go to 0.
How can I achieve that?
Set the slider value and trigger the change method.
Basic idea below and I added code that will unmute to the last known value instead of resetting it to 0.5.
const audio = { volume : 0 }
let lastVolume
const slider = $("#volume-slider").on("change", function() {
var val = +this.value;
audio.volume = val
if (val) lastVolume = val
console.log(audio.volume)
}).change();
$("#mute").on("click", function () {
var val = audio.volume === 0 ? (lastVolume || 0.5) : 0
slider.val(val).change()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="volume-slider" type="range" min="0" max="1" step="0.1" value="0.5"></input>
<button id="mute" type="button">Mute</button>