Don’t Stop The Music: Links on Pages Playing Audio

Avatar of Chris Coyier
Chris Coyier on

Over at ShopTalk, we’ve gotten a number of requests from folks that wished links in our show notes would open in a new tab. They’ve gotten burned by clicking a link on the page while listening to a podcast via our embedded player. When the browser leaves our page and goes to the link, the audio stops playing. We can do something about that.

One option would be to literally apply a target attribute to each link, so that those links open in a new window or tab.

<a href="#" target="_blank">Show Note Link</a>

We would have to go through our whole archive of shows to add that right to the HTML. Not un-doable, but not great and also not very flexible.

Personally I don’t generally like new tab links and I think that’s the general UX consensus as well. Don’t mess with the default unless you have a good reason. We do have a good reason here, but if we think a bit more about it, what we’re actually trying to do here is prevent the sound from abruptly stopping. So let’s only alter that behavior when the audio is actually playing.

We’re using MediaElements.js for the player and also jQuery on the page. This player provides events we can bind to for starting and stopping of audio.

var player = $('audio').mediaelementplayer();

$(player).on("play", function(event) {

  // Links in new tabs
  $("a").attr("target", "_blank");


Cool. You could get fancier with that, by removing the attribute on pause. I’ll let you decide how you want to handle it.

But what if you hate changing default behavior like this? That’s understandable. There is another way we could do this, and that’s using the onbeforeunload event (fires when the browser is about to change pages) to confirm the navigation.

It’s plenty easy. We just need to remove it when the audio isn’t playing.

var player = $('audio').mediaelementplayer();

$(player).on("play", function(event) {

  window.onbeforeunload = function() {
    return "The podcast will stop playing if you navigate away.";

}).on("pause", function(event) {

  window.onbeforeunload = void(0);


Both ways work. I went with the target=”_blank” technique for ShopTalk, but CodePen uses onbeforeunload quite a bit when you have unsaved changes to work, to prevent you from losing it. Also related: in the past we’ve bent over backwards making a whole site Ajax to prevent audio from stopping as you navigated around.