Mike Thrussell
Mike Thrussell

Reputation: 4525

How to remove dynamically created audio element in javascript?

Every 30 seconds I refresh a script to check for changes. The returned data sets the src for an audio element.

If the data has changed, I change the src attribute to match, but onClick - I hear both audio files play together.

What's happening here and how can I remove the previous audio file?

(function fetchCal() {
$.getJSON('events', function(data) {

//I need to clear any previously created elements here

  var nowAudio = document.createElement('audio');
  nowAudio.setAttribute('src',"audio/"+data.uid+"."+data.nowTitleURL+".mp3" );

  $('.now').click(function() {
      nowAudio.play();
  });

})
setTimeout(fetchCal, 30000); //refresh calendar every 30 secs
})();

note: $( "audio" ).remove(); didn't work

Upvotes: 0

Views: 2341

Answers (1)

epascarello
epascarello

Reputation: 207527

You are binding multiple clcicks to the same element so it will always have the previous click events. You would need to unbind it.

$('.now').off("click.audio").on("click.audio", function() {
  nowAudio.play();
});

Upvotes: 2

Related Questions