I’m attempting to make several audio elements in html that will play music when I tell them to via javascript.
Here’s my html:
<div id="pixelbutton" onClick="musicplay1()"> </div>
<audio id="song1" src="audio/ruins.wav" autostart=false hidden=true> </audio>
And my Javascript:
function musicplay1() {
var song1 = document.getElementById("song1");
song1.setAttribute('autostart', 'true');
}
The audio is for a good reason, so please spare me the “Oh god, really!? You’re putting sound on a webpage? That’s really annoying.” comments.
Question is: How can I feasibly create a function in javascript that controls when my html audio tag plays?
I’m rather new to JavaScript, so any help is appreciated.
You haven’t asked a question, but I can see a couple of things to improve:
autostartandhiddenare boolean attributes, but that doesn’t mean you should treat them like boolean variables. If the attribute is present then it is considered on, otherwise it’s considered off. There is no attributehidden– an<audio>element is only shown if thecontrolsattribute is set. Additionally, you should tell the browser what type of audio you’re using. So, your audio tag should be:1as a parameter, so you would have:autostartattribute probably won’t make it automatically start. Instead, use the.play()method. With this and the above point, you get:Hope this helps.