I am using HTML and Javascript for a drag and drop activity; dragging pictures onto targets.
In my example, I have two pictures, 'Horse' and 'Cow', and one target. I have two sound files, 'Neigh' and 'Moo'.
If I drag 'Horse' onto the target I want 'Neigh' to play. If I drag 'Cow' onto the target I want 'Moo' to play. The playing should be triggered by a button click.
I have code for the drag and drop but cannot do the sound playing.
EDIT: I know how to play sound files; I don't know how to play a specific file based on the position of an associated picture. Code is below: The function for the play button just plays a given sound file, it isn't controllable in any sense. This is what I need to change.
Thanks for any help :-)
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
/* this is the DROP function*/
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
/* plays the snippets when they are clicked clicked*/
function playAudio(url) {
new Audio(url).play();
}
/*Funcn for play button */
function play_music() {
document.getElementById("music1").play();
}
#empties {
width: 410px;
height: 700px;
margin-left: 10px;
margin-top: 0px;
position: absolute;
top: 10px;
left: 0px;
border: 1px solid blue;
}
.box001 {
width: 410px;
height: 41px;
margin: 0px;
padding: 0px;
border: 1px solid blue;
}
/* snippets */
#music {
width: 410px;
height: 700px;
margin-left: 00px;
margin-top: 0px;
position: absolute;
top: 10px;
left: 450px;
border: 1px solid red;
}
.box002 {
width: 410px;
height: 41px;
margin: 0px;
padding: 0px;
border: 1px solid red;
}
/* play button */
#my_button {
margin-left: 00px;
margin-top: 0px;
/*padding:10px;*/
/*border:1px solid black;*/
position: absolute;
top: 10px;
left: 880px;
border: 1px solid red;
}
<!-- music is dropped into these empty boxes -->
<div id="empties">
<div class="box001" ondrop="drop(event)" ondragover="allowDrop(event)" id="place001"></div>
</div>
<!-- these are the snippets to be dragged and dropped -->
<div id="music">
<div class="box002" ondrop="drop(event)" ondragover="allowDrop(event)">
<img onclick="playAudio('neigh.mp3')" ondragstart="drag(event)" draggable="true" id="target001" src="horse.JPG" alt="" border="0" />
</div>
<div class="box002" ondrop="drop(event)" ondragover="allowDrop(event)">
<img onclick="playAudio('moo.mp3')" ondragstart="drag(event)" draggable="true" id="target002" src="cow.JPG" alt="" border="0" />
</div>
</div>
<!-- Audio for button-->
<audio id="music1" src="neigh.mp3" preload="auto"></audio>
<!-- Button -->
<div id="my_button">
<button onclick="play_music()" ;>Play</button>
</div>