[SOLVED] I am trying to call two functions with one button – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by aagney krishna

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



Solution

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.


This Question was asked in StackOverflow by aagney krishna and Answered by Merlin the Immortal It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?