Add play audio event to many many elements in different scenes

Hi! I want to add a mouseClick action to many many elements in different scenes, let them play an audio which I’ve already upload to the hype document. But I don’t know how to write the code. Now I write them in the header HTML:

<script> HYPE.documents['cloud5','cloud4','cloud3','cloud2','cloud1'].event['onMouseClick'];
var myAudio = hypeDocument.documentName('so.mp3');
myAudio.play();
</script>

I want to do that: when I click on the elements named “cloud5”,“cloud4”…, the audio “so.mp3” will play.

I have 30 hype documents and there are 10 scenes which include 3 layouts in a document, every layouts has some elements need to be added the "play audio"events…I don’t want to add the event one by one…it’s crazy. Here’s an example:play audio.zip (484.6 KB)

Thank you very much!~~~

It sounds like you want “Event Delegation”.

Instead of adding actions or event listeners to every element, you could add an event listener to the whole page. Then, when an element is clicked, you could get the ID of the element clicked. Once you have the ID of the clicked element, you can use a conditional. If element clicked is cloud 1, or cloud 2, or cloud 3... then do something... such as playing the sound effect.

If only your sound related elements include the word “cloud”, you could also use the indexOf() method to see if the clicked element contains the word “cloud”.

2 Likes

@Photics, love it, Never really used this bubbling effect, but it works very well in Hype.

@lydialmz,

I am right in thinking that these Hype documents are all being loaded into an external page?.
If so you would need to put the code in the parent head file.

Working from the first link in the stack overflow link above the code would be similar to this.

	<script> 

document.addEventListener("click",function(e) {
	// e.target was the clicked element
  if (e.target && e.target.matches(".cloadSound")) {
    console.log(e.target.id, "Sound element clicked!");
    
	}
});
 
</script>

note I give every cload a class name of ‘cloadSound’

1 Like