Changing sound effect on a function when variable changes

127 Views Asked by At

I'm writing a homework assignment for a JS class, and the teacher wants us to have a weapon sound when firing, but stop making sound when out of ammo. I have the sound effect working for when the gun fires, but it continues making the sound when clicked with 0 ammo.

I tried doing an else{} function, but this breaks the "ammo display" in my browser, and the sound would continue playing anyway.

HTML:

<input type="button" value="Heal" class="shoot" onclick="shoot();">
<audio id="heal" src="sound/heal.mp3">

JS: Displays ammo starting at a maximum of 6 shots, with 6 shots in reserve, and counts down each time it is fired.

function shoot() {
  if (currentAmmo > 0) {
    currentAmmo--;
  }
  var shoot = document.getElementById("shoot");
  shoot.play();
  updatescreen();

  function updatescreen() {
    document.getElementById("total-ammo").innerHTML = "Bullets in Gun:</br>" + totalAmmo;
    document.getElementById("current-ammo").innerHTML = "Reload Ammo:</br>" + currentAmmo;
  }
2

There are 2 best solutions below

0
obscure On BEST ANSWER

You just need to move the play command inside the if-condition.

  if (currentAmmo > 0) {
    currentAmmo--;
  var shoot = document.getElementById("shoot");
  shoot.play();
  }

  updatescreen();
0
Jack Bashford On

Place the play call inside your if statement, so it plays only if the statement is true:

function shoot() {
  if (currentAmmo > 0) {
    currentAmmo--;
    document.getElementById("shoot").play();
  }
}