What I want to do is when the user refreshes the page, either the red, blue, green or yellow buttons will be animated and the sound will be played. Although the animation works, the sound doesn't. I tried using the basic var green = new Audio("sounds/green.mp3"); and green.play(); but no sound appears
JavaScript
let buttonColours = ["red", "blue", "green", "yellow"];
let gamePattern = [];
function nextSequence() {
var randomNumber = Math.round(Math.random()*3);
return randomNumber;
}
var randomColor = buttonColours[nextSequence()];
animateButton();
gamePattern.splice(0,0,randomColor);
function animateButton() {
if (randomColor=="green"){
$("#green").css("opacity", "0.6");
setTimeout(function() {
$("#green").css("opacity", "1");
}, 100);
var green = new Audio("sounds/green.mp3");
green.play();
}
if (randomColor=="blue"){
$("#blue").css("opacity", "0.6");
setTimeout(function() {
$("#blue").css("opacity", "1");
}, 100);
var blue = new Audio("sounds/blue.mp3");
blue.play();
}
if (randomColor=="red"){
$("#red").css("opacity", "0.6");
setTimeout(function() {
$("#red").css("opacity", "1");
}, 100);
var red = new Audio("sounds/red.mp3");
red.play();
}
if (randomColor=="yellow"){
$("#yellow").css("opacity", "0.6");
setTimeout(function() {
$("#yellow").css("opacity", "1");
}, 100);
var yellow = new Audio("sounds/yellow.mp3");
yellow.play();
}
}
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>
<body>
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
<div class="row">
<div type="button" id="green" class="btn green"></div>
<div type="button" id="red" class="btn red"></div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow"></div>
<div type="button" id="blue" class="btn blue"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src = "game.js"></script>
</body>
</html>