HTML5 Guidelines for Web Developers

(coco) #1
4.8 And What About Audio? 103

loadTrack() is called in various ways. First, when changing tracks directly in the
menu via the onchange event handler changeTrack(this):


changeTrack = function(ctrl) {
loadTrack(ctrl.options.selectedIndex);
};


Of course it is also called by the Skip forward and Skip backward buttons; their
respective onclick event handler calls the callback function advanceTrack(n)
and passes it the step value in the argument n as well as the desired direction
via the positive or negative sign. The step value is the same in both cases, which
means -1 is skip backward and 1 is skip forward:


advanceTrack = function(n) {
var idx = tracks.options.selectedIndex + n;
if (idx < 0) {
idx = idx + tracks.options.length;
}
if (idx > tracks.options.length-1) {
idx = idx - tracks.options.length;
}
tracks.options.selectedIndex = idx;
loadTrack(idx);
};


The algorithm for determining the new track is simple and consists of two
phases. We first add n to the index of the selected track, and then we deal with
two special cases that may arise from this: If we are currently in the first track
and click Skip backward, the index becomes negative and we therefore have to
keep playing the last track. If we are in the last track and click Skip forward, this
also does not work, so we have to make sure the player selects the first track as
next track.


The advantage of the method advanceTrack() is that we can use it even for the
last two features—looping at the end of the track and random track selection.
First, we quickly need to discuss exactly how the two buttons signal inactive and
active. Switching between the two modes is done via onclick event handlers,
which trigger the callback toggleOnOff(node) and assign the appropriate button
in the argument node:


toggleOnOff = function(node) {
var cls = node.getAttribute("class");
node.setAttribute("class",
(cls == 'off')? 'on' : 'off'
);
pbStatus[node.id] = node.getAttribute("class");
};

Free download pdf