Time for action – playing the notes

The next thing we need to do is add event handlers to play an <audio> element when a piano key is clicked or touched. We will hook up and event handlers to all of our piano keys and play the associated note when they are fired.

Note

At the time of this writing, the state of audio on mobile devices isn't very good. Although a touch device would be perfect for a piano app, the sounds don't always play correctly because of the way mobile browsers cache audio (or not).

Let's create a method called initKeyboard() that will be called from the application's start() method:

function initKeyboard() { var $keys = $(".keyboard .piano-key"); if ($.isTouchSupported) { $keys.touchstart(function(e) { e.stopPropagation(); e.preventDefault(); ...

Get HTML5 Web Application Development By Example Beginner's guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.