1

I have encountered a slight difficulty within my code. Following function is involved in a part of a small game for private use. My question is, how can add a sound if the image generated is clicked on?

Code:

function img1() {
    var img = document.createElement('img');
    img.src = "img1.png";
    document.body.appendChild(img);
    img.className = "img1";
}

I'd like this soundfunction to be triggered on click:

function sound1() {
    var audio = new Audio('s1.wav');
    audio.play();
}
Lionel Renaux
  • 152
  • 1
  • 14
Eppes
  • 23
  • 4

1 Answers1

0

You need to assign the click event to the image

function img1() {
    var img = document.createElement('img');
    img.src = "img1.png";
    document.body.appendChild(img);
    img.className = "img1";
    img.addEventListener( "click", sound1, false ); //this line has been added
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94