Java Reference
In-Depth Information
The HTML in this example is untouched from Example 2, so let's jump right to the code. Outside of
any function, you define three variables for referencing the
<video/>
and two
<button/>
elements:
var video = document.getElementById("bbbVideo");
var playButton = document.getElementById("playbackController");
var muteButton = document.getElementById("muteController");
You'll use these variables throughout the various functions, but first, you register the event listeners.
For the
<video/>
element, you register
pause
,
playing
, and
volumechange
event listeners:
video.addEventListener("pause", pauseHandler);
video.addEventListener("playing", playingHandler);
video.addEventListener("volumechange", volumechangeHandler);
Each event listener uses a unique function—the
pauseHandler()
function handles the
pause
event,
playingHandler()
handles the
playing
event, and
volumechangeHandler()
handles the
volumechange
event. You could make the argument that the
playing
and
pause
event code is similar
enough to use a single function, but keep it simple! Simple functions are happy functions.
And once again, the two
<button/>
elements register
click
events using the
playbackClick()
and
muteClick()
functions:
playButton.addEventListener("click", playbackClick);
muteButton.addEventListener("click", muteClick);
Each of the five functions in this example is reduced to a single responsibility. This is a good thing
because it makes your code easier to manage and maintain (as well as find and fix errors if they occur).
The first function is the
pauseHandler()
function, which as you know, handles the media's
pause
event:
function pauseHandler(e) {
playButton.innerHTML = "Resume";
}
Its job is simple; change the text of the Play/Pause button to Resume when the
pause
event fires. This
way, the button's text changes as the state of the video changes.
The next function is
playingHandler()
, the counterpart to the
pauseHandler()
function:
function playingHandler(e) {
playButton.innerHTML = "Pause";
}
When the media plays, this function changes the Play/Pause button's text to Pause.
The
volumechangeHandler()
function is slightly more complicated because it fires for two types of
events—when the volume changes and when the media is muted:
function volumechangeHandler(e) {
muteButton.innerHTML = video.muted ? "Unmute" : "Mute";
}