Snow
Snow

Reputation: 47

Can javascript be used for two buttons at once?

I've recently been learning / working with javascript, and can get it to work OK. However, I don't seem to be able to get it to play 2 buttons hit at the same time.

For example, [button1] [button2]

where each has a different sound programmed to it. You can hit each one and get a sound, but when you hit both, you don't get any sound.

Is there a way to get both to play their sounds when you hit them both?

Thanks

...

my code if relevant:

  <button id="Eb3btn"></button>
  <button id="Fbtn"></button>

  <script src="<?php bloginfo('stylesheet_directory'); ?>/javascript/howler.js/howler.min.js"></script>
  <script>
      var Eb3 = new Howl({urls: ["<?php bloginfo('stylesheet_directory'); ?>/sounds/Eb3.mp3"]})
      document.getElementById('Eb3btn').onclick=function(){Eb3.play()};

      var F3 = new Howl({urls: ["<?php bloginfo('stylesheet_directory'); ?>/sounds/F3.mp3"]})
      document.getElementById('Fbtn').onclick=function(){F3.play()};
  </script>

Upvotes: 1

Views: 681

Answers (1)

Jonathan.Brink
Jonathan.Brink

Reputation: 25383

JavaScript runs within a single execution thread so you will never be able to get them to click truly 100% at the same time.

The closest you can get to having them be clicked together is:

var btnEb3 = document.getElementById('Eb3btn'),
    btnF = document.getElementById('Fbtn');

btnEb3.click();
btnF.click();

Some more information about JavaScript threads: Why doesn't JavaScript support multithreading?

So, putting my snippit with your example could look something like:

<script>
var Eb3 = new Howl({urls: ["<?php bloginfo('stylesheet_directory'); ?>/sounds/Eb3.mp3"]})
document.getElementById('Eb3btn').onclick=function(){Eb3.play()};

var F3 = new Howl({urls: ["<?php bloginfo('stylesheet_directory'); ?>/sounds/F3.mp3"]})
document.getElementById('Fbtn').onclick=function(){F3.play()};

// have Eb3 and F play together:
document.getElementById('Eb3btn').click();
document.getElementById('Fbtn').click();
</script>

Upvotes: 1

Related Questions