HTML and CSS Reference
Click-and-Drag Volume Slider
Sonowwemakeittothelast,butcertainly notleast,pieceoffunctionality fortheaudioplay-
er: the volume slider. The volume slider is an interactive control allowing the user to manipu-
late it by sliding it right or left to control the volume of the playing audio element. Before we
create the volume slider, we need to define some boundaries for its usage:
▪ The slider never moves on the y-axis; it will always keep a y value.
▪ Thefartherthevolumeslideristotheright(thegreaterthe x value),thehigherthevolume.
▪ The slider moves on the x-axis but is bounded by the starting x value of the volume slider
image— volumeSliderStart on the left and volumeSliderEnd on the right.
▪ When the user clicks on the volume slider, we will assume that the user wants to set the
on the x-axis, we will move the slider accordingly.
▪ When the user takes his finger off the mouse button, we will assume that he no longer
wishes to set the volume, and we still stop “dragging” the slider.
▪ The volume will be set based on the slider's position on the x-axis in relation to the
volumeSliderStart plus a ratio ( volumeIncrement ) that we create describing how
much volume to increase or decrease based on where the slider rests.
Volume slider variables
Now that we have thoroughly confused you, let's talk about the process in depth. First, we
startwiththe canvasApp() function.In canvasApp() ,weneedtosetupsomevariablestoset
the rules we defined in the list above.
The starting x position for the volume slider is volumeSliderStart . When the application
starts, it is equal to the x position of the volume background, or volBackX . This means that it
will start at the leftmost edge of the volume slider where the volume will be set to 0 . We will
update this to the correct position based on the volume as soon as we calculate that value:
var volumeSliderStart = volBackX ;
The final x position for the volume slider is volumeSliderEnd , which is the rightmost posi-
tion. It is the position where the volume will be set to 100% (or 1 ). This position lies at the x
position of volumeSliderStart plus the width of the volume slider background ( volBackW ),
less the width of the volume slider itself ( sliderW ):
var volumeSliderEnd = volumeSliderStart + volBackW - sliderW ;