With Javascript, I have a function that creates an audio element with createElement("audio")
, and start playing in loop without using appendChild()
, I mean without appending it to the DOM.
The element created is kept in a variable, let’s called it music1
:
music = document.createElement("audio"); music.addEventListener("loadeddata", function() { music.play(); }); music.setAttribute("src", music_Source);
What I would like to do, is to change the music played, if possible using the same function, and storing the element in the same variable.
What I do is that before the code above:
if(typeof(music) == "object") { music.pause(); music = null; }
But: if I remove music.pause()
, the first music keeps playing, and the second starts playing too at the same time, which makes me think that the first music is always somewhere in the document/in the memory. Also, music = null
seems useless. I don’t want to use jQuery.
Do you have any idea to properly remove the first music, delete the element, or so on?
Actually, kennis’ comment is right, I tried to just change the src attribute, and not modify the “music” variable (neither setting it to null, nor re-creating an Element) and it seem to work too. So, for the record: For each source changing here is the function:
if(typeof(music) != "object") { //audio element does not exist yet: music = document.createElement("audio"); music.addEventListener("loadeddata", function() { music.play(); }); } music.setAttribute("src", music_Source);
Advertisement
Answer
rather than delete, the better way of doing it would be to change the src
music.setAttribute('src',theNewSource); //change the source music.load(); //load the new source music.play(); //play
that way you’re always dealing with the same object so you hit the DOM less often, and also you avoid your problem of having two player at the same time
Also make sure you use the .load method to load the new audio, otherwise it will keep playing the old one.