I have a custom volume bar and mute button in my music player. Muting is very simple, but I want to return the previous volume when the button is clicked for the second time.
Example: Let's say the current volume is at 50%. Clicking the mute button will change it to 0. Clicking it again should get it back to 50%.
This is how I tried it:
var music = document.getElementById('music');
var volumehead = document.getElementById('volume-head');
var volumebar = document.getElementById('volume-bar');
var mute = document.getElementById('mute');
mute.addEventListener("click", muteSound);
function muteSound(){
if(mute.classList.contains('not-muted')){
// Save current values before changing them
var lastHead = volumehead.style.marginLeft;
var lastVolume = music.volume;
// Change classname for appearance and next click
mute.className = "muted";
// Change values to 0
volumehead.style.marginLeft = "0px";
music.volume = 0;
} else {
// Change classname for appearance and next click
mute.className = "not-muted";
// Use saved values
volumehead.style.marginLeft = lastHead;
music.volume = lastVolume;
}
}
The 2 variables that hold the position of the handler and the volume are declared within the if-statement, meaning they're not accessible in the else-statement.
Declaring them outside of the statements means that the values will be "overwritten" by 0.
Is there a way to save the values and use them for the next click on the button?
Aucun commentaire:
Enregistrer un commentaire