Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
How to produce a sound associated to a color automatically when a random function produces the color to in javascript

In the code, I am generating random color from the array and I want to produce sound related to it.

Here is the javascript code

var gamePattern = [];
var buttonColours = ["red", "blue", "green", "yellow"];
var randomChosenColour = buttonColours[nextSequence()];
gamePattern.push(randomChosenColour);


function nextSequence() {
  return Math.floor(Math.random() * 4);
}



$("." + randomChosenColour).fadeOut(100).fadeIn(100);

$("." + randomChosenColour).ready(function(){
  var audio = new Audio("sounds/"+ randomChosenColour +".mp3");
  audio.play();
});

here is the html code

<div class="container">
    <div lass="row">

      <div type="button" id="green" class="btn green" >
        <!-- <audio id="sound" src="sounds/green.mp3"></audio> -->
      </div>

      <div type="button" id="red" class="btn red" >
        <!-- <audio id="sound" src="sounds/green.mp3"></audio> -->
      </div>
    </div>

    <div class="row">

      <div type="button" id="yellow" class="btn yellow" >
        <!-- <audio id="sound" src="sounds/green.mp3"></audio> -->
      </div>
      <div type="button" id="blue" class="btn blue" >
        <!-- <audio id="sound" src="sounds/green.mp3"></audio> -->
      </div>

    </div>

  </div>

I tried many ways to produce sounds but I am getting errors in the console.

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

Any help here would be appreciated.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!