HTML and CSS Reference
In-Depth Information
If you're not using XHTML syntax as we do throughout the topic, the code
would read:
<audio src=”assets/fb_demo_song.mp3” controls></audio>
The controls attribute is a Boolean one and its presence, even without a value,
enables the attribute.
There are two scenarios in which you might want to leave out the controls attribute. Say you want
to have background music start playing when your page loads. In this situation, you would remove
the controls attribute and add an autoplay one, like this:
<audio src=”assets/fb_demo_song.mp3” autoplay=”autoplay”></audio>
This combination of attributes would cause the designated song to begin playing immediately when
the browser is ready. Though this might be gratifying to the song's creator, not all web visitors enjoy
a sudden burst of music. It's a good idea to offer a way to mute or stop playing the song. Luckily, the
<audio> tag supports a number of key JavaScript functions — which can also be used to create cus-
tom buttons, the second scenario where you might want to hide the native controls.
If you just wanted to pause the music, you could create a button with a little JavaScript attached,
like this:
<audio id=”mySong” src=”../assets/fb_demo_song.mp3” autoplay=”autoplay”></audio>
<button onclick=”javascript:document.getElementById('mySong').volume=0;” >
Mute Music</button>
You'll notice that the <audio> tag now has an id attribute, which makes it easier for the JavaScript
function to properly target the tag. The onclick event handler in the <button> tag pinpoints the
<audio> tag and sets the volume to zero when clicked. Another option would be to change to but-
tons to play and pause, as shown in Figure 24-6. This is accomplished with the following code:
<audio id=”mySong” src=”../assets/fb_demo_song.mp3” autoplay=”autoplay”></audio>
<button onclick=”javascript:document.getElementById('mySong').pause();” >
Pause Music</button>
<button onclick=”javascript:document.getElementById('mySong').play();” >
Play Music</button>
FiGure 24-6
Search WWH ::




Custom Search