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 given a value within the if-statement, meaning they don't have one 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?
Edit (solution):
The values that the if-statement assigned to the variables, could only be used by the else-statement if the variables were declared outside of the function.
var, they're hoisted to the top of the function. A variable is only scoped to a statement block when usingletorconst. Anyway, the solution to your issue is to declare the variables outside of the functionmuteSound, i.e. together where all your othervolumebarvariables etc. are. Conceptually: you should attach an event handler to the volumebar which updates thatvolumevariable every time it's moved; sovolumealways contains the currently chosen volume. Whenmuteis clicked you mute the volume and render your UI to indicate a muted volume; you do not change the value ofvolume. When unmuting you restore the volume and update the UI again.undefined.undefined, it would throw aReferenceErrorsayinglastHead is not defined. You can see the difference for yourself by changingvartolet.