Load Music Dynamically From a Clickable Image

Did I mention "interesting user experiences"? How about a jquery based music player that also works on mobile devices such as the Iphone? To see how such a contraption could work, open jukebox.html with Firefox (Not Chrome or Safari) and, while in live view, click on the pictures of musicians to load and play some music. 1 Those probably aren't your favorite songs but there is no reason why you can't build your own. Here's how it works.

1. Open jukebox.html in brackets and look at the code. To the right of abba.jpg you should see the code below that tells the browser to load the file named dq.html whenever someone clicks on the abba graphic. Dq.html actually plays the music.

onclick=$('#result').load('dq.html');>

3. Open dq.html and take a look between the body tags. As you can see, all it contains are three lines of code. The first line invokes html5's native audio controls as in: <audio controls="controls" autoplay="true"> while the second line targets a specific mp3 file in the same folder.

4. This html5 audio stuff is all well and good but there is one small hitch which I suppose we can blame on lawyers. The mp3 audio format is not open source and, in fact, is what is known as “patent encumbered”. This means that any organization that creates a web browser and wants their web browser to be able to play mp3 files, has to give someone some money in order to do so. These days, most major browsers support mp3 (Ie. they paid up)

If you run into this problem with some less prominent browser and  want to be sure that your sound files will play on these browsers as well, you will need to add an additional line of code that links to an additional sound file in either the ogg or wav format. To see how this works, open ww.html and take a look at the code that calls both an mp3 and an ogg file, each named WalkThisWay.  The good news is that there seem to be plenty of free mp3 to ogg converters available.

5. And that's all there is to it.

6. Now try it yourself. Open fader.html. As you can see, fader.html is set up to load twist.mp3, Chubby Checker's famous song. To give homage to the Beatles by playing one of their early tunes, substitute twist.mp3 for twistshout.mp3 and save as beatles.html.

7. Return to jukebox.html and add a line of code to the beatles picture like the one below that loads beatles.html into the result div tag.

onclick=$('#result').load('beatles.html');>

9. Test again in Firefox. If everything is done properly you should hear the Beatles.

Next: Loading Content (not html) into a Div Tag

Print Friendly, PDF & Email

  1. As in the previous lesson, there is a good chance that you will NOT be able to do this in Safari or Chrome because of restrictions unless you upload everything to a web server.