0

I have an image that changes the background of the page already but I would also like it to play music when I click the image. Here's My code

HTML:

<div id="background">
        <div id="box">
            <div class="button">
                <img src="alien.png" type="button" id="my-button">
                <br>
                <p>Click The Alien!</p>
            </div>
        </div>

JavaScript:

 <script>
var myData = {

        1: {
        imageUrl: "8.gif",

        },

};

function changeImage() {
        var randomNumber = Math.floor((Math.random() * 1) + 1);
        document.getElementById("background").style.background = "url('" + myData[randomNumber].imageUrl + "')";
        document.getElementById("text-box").innerHTML = myData[randomNumber].text;
}
    document.getElementById("my-button").addEventListener("click", changeImage);

double-beep
  • 5,031
  • 17
  • 33
  • 41
  • ` – StackSlave Feb 28 '15 at 23:10
  • [http://stackoverflow.com/questions/9419263/playing-audio-with-javascript][1] Check all the answers. [1]: http://stackoverflow.com/questions/9419263/playing-audio-with-javascript – BKFighter Feb 28 '15 at 23:13

2 Answers2

2

Depending on how well the Javascript Audio API is implemented in your chosen browser, you can use the AudioContext interface, documented at https://developer.mozilla.org/en-US/docs/Web/API/AudioContext.

edition
  • 638
  • 14
  • 31
-2
  <script>
    $(function(){
       $(document).("click", "img.class", function() {
          var audioElement = document.createElement('audio');  //creates audio element
          audioElement.setAttribute('src', audiopath);         //setpath to audio files.
          audioElement.setAttribute('autoplay', 'autoplay');   //set auto play attributes.
          audioElement.addEventListener("load", function() {
             audioElement.Play();                              //plays audio element.
          }, true);
       });
    });

Use audioElement for it.

user254153
  • 1,855
  • 4
  • 41
  • 84
  • What a terrible mess. Why is the indentation _all over the place_? What is `$.get()` supposed to do? Why do you have a commented-out line? Where is the explanation of your proposed solution? It truly baffles me that this nonsense has an upvote. – Lightness Races in Orbit Feb 28 '15 at 23:24