Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

HTML HTML Video and Audio (Retired) Media Basics The Audio Element

Rebecca Jasso
Rebecca Jasso
3,243 Points

Auto stop when playing other files

I'm making a website for a classical guitarist and there are 4 recordings that I'd like to put on a page as an example of his work. The problem I'm running into is that if you listen to a little bit of one and want to move on to the next, it is still playing the first. I know that in my own experience on SoundCloud and Bandcamp the audio from the first file will pause when I hit play on another track. I'd like this to happen on his page so that his potential clients will not have to futz around with the buttons on each player. How can I make this happen? By the way, I only know HTML and CSS so far, having not delved into JS just yet. Is this possible at my level? Or do I just need to move forward a little more?

3 Answers

Odair Assis
PLUS
Odair Assis
Courses Plus Student 15,669 Points

As far as i know it's not possible to do what you want without a litle bit of javascript. Just to give you a quick start:

// Listen to the 'play' event:
document.addEventListener('play', function(e){
    // Collect all <audio> elements in the page:
    var allAudios = document.getElementsByTagName('audio');
    // Iterate through all players and pause them, except for
    // the one who fired the "play" event ("target")
    for(var i = 0; i<allAudios.length; i++){
        if(allAudios[i] != e.target){
            allAudios[i].pause();
        }
    }
}, true);
Jason Dittmer
Jason Dittmer
8,273 Points

To be honest, I would just use Wordpress and an audio player plugin. There are several plugins that you could try. Like this one: https://wordpress.org/plugins/compact-wp-audio-player/

Travis Thompson
Travis Thompson
12,976 Points

I would suggest using soundcloud and embed the audio player. This can be done without knowing Javascript. You can see this on my site here: http://www.ancient-digital.net