Create a Single Play Button using Bootstrap & jQuery

Play / Pause toggle example for your music site needs.

Posted by Michael Bordash on Thu Sep 11, 2014


As I was re-designing the song pages on InternetDJ, I wanted to optimize the UX by condensing the use of buttons and other controls that play a song on a page. I've recently switched from the JW FLV player to using the simple HTML5 audio element which is now supported by the most important browsers. However, the default look/feel in Chrome/Firefox looked a bit too large to me and has unnecessary controls like volume control, seek bar, and time (for the latter two controls I'm using peaks.js). I really need just a simple play/pause button for sound control.

Since I use Bootstrap3 and jQuery, I was able to quickly whip up a small play/pause button, you can see how it looks on any of the song pages, such as this one. If you'd like to use this in your site, here's how to do it.

First, I create the play and pause buttons indepedently using the Bootstrap button class and included glyphicons.  I'm not a fan of sites that start playing sound when the page loads, so the default state on InternetDJ is stopped.  Note below that the the pause button has the hide class added to prevent display.

<audio id="peaks-audio" preload="auto">
  <source src="" type="audio/mpeg">
   Your browser does not support the audio element.

<button id="idj-play-button" class="btn btn-xs"><i class="glyphicon glyphicon-play"></i></button>
<button id="idj-pause-button" class="btn btn-xs hide"><i class="glyphicon glyphicon-pause"></i></button>

Next, you'll need to include some JavaScript.  This is also pretty simple.  Using jQuery, we'll simply detect and handle the click events for Play and Pause. For example, when the user clicks the Play button for the first time, it will begin playing the audio, then flip the hide class from the Play to the Pause buttons. The Pause button will now appear to the user for interaction. Also, you'll want to detect when the audio has ended in order to rewind the song and flip back to the Play button. Here's the code:

$('#idj-play-button').click(function() {
$('#idj-pause-button').click(function() {

$('#peaks-audio').on('ended', function() {


And that's it. Clearly there are a lot of ways to do this sort of thing, so if you have a better means please feel free to comment below. Here's the JSFiddle.




Recommended For You

Article Comments