Inspired by soundboard sites such as iDaft, I wanted to add audio events to the animated menu bar I made in part one of this series. While web sites should only “speak when spoken to”, and leave initiation of playback up to the user, I was willing to craft an exception due to the fact that the code is a proof-of-concept for a music site.
Sans Flash or other plugin, we can add sound to a webpage in two ways: either instancing the audio solely through JavaScript, or by embedding the sound on the page with the <audio>
tag. In this case, we need to add four sounds, one for each link:
<audio preload="auto" id="harder" src="harder.mp3">
<audio preload="auto" id="better" src="better.mp3">
<audio preload="auto" id="faster" src="faster.mp3">
<audio preload="auto" id="stronger" src="stronger.mp3">
Note that the audio is effectively hidden on the page by the absense of a controls
attribute. We could add an alternative version of audio short audio track in another codec to cover older browsers, if needed.
An id
should be added to each link in order to address them with JavaScript:
<nav id="equalizer">
<a href="#" data-ref="harder">Beats</a>
<a href="#" data-ref="better">Samples</a>
<a href="# data-ref="faster">Loops</a>
<a href="#" data-ref="stronger">Rhythms</a>
</nav>
The next part is addressing each audio source and linking it to the mouseover state of link. This can be achieved with a few lines of JavaScript:
function playtrack() {
var track = document.querySelector("#"+this.dataset.ref);
track.play();
}
function triggertrack(element) {
element.addEventListener('mouseover', playtrack, false);
}
var musictriggers = [].slice.call(document.querySelectorAll("#equalizer a"));
musictriggers.forEach(triggertrack);
I could extend this by making a true graphic equalizer effect with the Web Audio API, a technique I'll address in a future article.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/EaNMJw