Reputation: 90
I'm trying to write some JS that will change a square from blue to yellow if the audio has played for a second or more. Currently, no change seems to happen at all. This is the first bit of JS that I've tried writing by myself, so if anyone has a tip that would be awesome.
// sound from https://www.w3schools.com/tags/horse.ogg
// when one second or more of the audio is played, change the square from blue to yellow
window.onload = function() {
function changeColor() {
var timedChange = document.getElementById("audioPlayer").currentTime;
if (timedChange >= 1) {
document.getElementById("yellow").style.display = "block";
} else {
document.getElementById("yellow").style.display = "none";
}
};
}
#blue {
width: 200px;
height: 200px;
background-color: blue;
}
#yellow {
width: 200px;
height: 200px;
background-color: yellow;
position: absolute;
top: 8px;
display: none;
}
#audioPlayer {
position: absolute;
right: 500px;
top: 10px;
}
<div id="blue"></div>
<div id="yellow"></div>
<audio id="audioPlayer" src="https://www.w3schools.com/tags/horse.ogg" type="audio" onclick="changeColor()" controls>
</audio>
Upvotes: 0
Views: 62
Reputation: 73
const audio = document.getElementById("audioPlayer");
// show yellow square after 1sec (1000 millisec) of audio playback
audio.onplay = () => {
setTimeout( () => {
document.getElementById("yellow").style.display = "block";
}, 1000);
};
// hide the yellow square immedeately when the audio stops
audio.onpause = () => {
document.getElementById("yellow").style.display = "none";
};
#blue {
width: 200px;
height: 200px;
background-color: blue;
}
#yellow {
width: 200px;
height: 200px;
background-color: yellow;
position: absolute;
top: 8px;
display: none;
}
#audioPlayer {
position: absolute;
right: 500px;
top: 10px;
}
<div id="blue"></div>
<div id="yellow"></div>
<audio id="audioPlayer" src="https://www.w3schools.com/tags/horse.ogg" type="audio" controls>
</audio>
Upvotes: 1
Reputation: 48612
Three problems:
timedChange: function()
, either do timedChange = function()
or function timedChange()
.Upvotes: 0