user3152117
user3152117

Reputation: 13

Stopping an audio element by ID

Thanks for checking out my question. I'm running into a stumbling block stopping an audio element and I'm hoping to get some help. I'm creating audio elements dynamically with arguments, like this.

var audio = document.createElement("audio");
audio.setAttribute('id', params[0]);

This works fine, params[0] is a user argument. I can alert audio.id and I get 'backgroundmusic' for example. And audio.play works. The problem comes when I try to stop it.

var audio = document.getElementById(params[0]);
audio.pause();

I thought this would work, but it returns null every time. I'm a total javascript rookie and Im sure this is a rookie mistake, but what am I doing wrong?

Thank you very much in advance.

Upvotes: 1

Views: 363

Answers (2)

Allan Chua
Allan Chua

Reputation: 10175

I had observed that you did not attached the audio object to the DOM/Document. This causes document.getElementByID to fail in finding the element. the easiest way to stop the audio file from playing is to keep a reference to the audio object that you created.

var audioControl;

function CreateAudioElement(params)
{
    audioControl = document.createElement("audio");
    audioControl.setAttribute('id', params[0]);
}

function StopAudioElement()
{
  audioControl.pause();
 }

Upvotes: 0

suren
suren

Reputation: 981

After creating the audio element, append it to some element in the dom.

var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'http://home.tiscali.nl/~jvanderw/malaysia02/sounds/greatargus.mp3');
    audioElement.setAttribute('id', "user_id");
    audioElement.load()
$("#audio_div").append(audioElement); 

I created a fiddle, check this http://jsfiddle.net/QG68M/

Upvotes: 1

Related Questions