I am trying to call two functions with one button

Viewed 58

This is my code

<!DOCTYPE html>
<html>
  <head>
    <style>
        image {
            display: none;
        }
      </style>
    <body>
      <input type= "text4" id = "text567">
      <input type= "text5" id = "text568">
      <button id="" onclick = area()> area </button>
      
      <img id="78454" src= >
      <script>
        function area()
          {
            let image= document.getElementById("78454")
            image.src="scary.gif"
            image.height="1500"
            image.width="1500"
          }
        function sound()
          {            
            var snd = new Audio(scream.mp3)
            snd.play()
          }
      </script>
    </body>
  </head>
</html>

(scary.gif is a image and scream.mp3 is obvious) I am trying to make the button play the sound and play the image but it either plays the image and doesn't play the sound or doesn't show both. Can you help with this

4 Answers

There are multiple ways to do so:

Call a function that calls two functions

As others said, it's a pretty good way to do so:

function callBoth() {
   area();
   sound();
}

Call the two functions in the button's onclick attribute

<button onclick="area(); sound();">The button</button>

Call both functions in an anonymous function

document.getElementById("BUTTONID").addEventListener("click", function() {
   area();
   sound();
});

...and many more other ways.

You can define a function that calls the other two functions.

function playImageAndSound() {
  area();
  sound();
}

Alternatively, you could merge the two functions.

function playImageAndSound() {
  let image = document.getElementById("78454")
  image.src="scary.gif"
  image.height="1500"
  image.width="1500"

  var snd = new Audio(scream.mp3)
  snd.play()
}

wrap your functions in another function and call that -

function handleClick () {
 area();
 sound()
}

and usage -

onclick="handleClick()"

Issues that I identified.

  • You have not called the sound function.
  • The link mentioned in the sound function as the parameter for new Audio must be a string, which is the link to the audio file.

Working Code

function area() {
  let image = document.getElementById("78454");
  image.src =
    "https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-play-512.png";
  // image.height = "1500";
  // image.width = "1500";
  image.height = "150";
  image.width = "150";
}
function sound() {
  var snd = new Audio(
    "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
  );
  snd.play();
}
<input type="text4" id="text567" />
<input type="text5" id="text568" />
<button id="" onclick="area(); sound()">area</button>

<img id="78454" src= >

Related