Issue
I've got this jquery code and html to work OK for an English language training site.
$(document).ready(function() {
$("p").hover(
function() {
$(this).css({"color": "purple", "font-weight" : "bolder"});
},
function() {
$(this).css({"color": "black", "font-weight" : ""});
}
);
$("p").click(function (event) {
var element = $(this);
var elementID = event.target.id;
var oggVar = (elementID +".ogg");
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', oggVar);
audioElement.load();
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);
audioElement.play();
});
});
<div>
<p id="one"> this is the first paragraph</p>
....
<p id="four"> this is the fourth paragraph</p>
....
</div>
the problem is that if text is clicked on while an audio file is playing (or double clicked) then the second file (or the same file) starts playing. So I end up with two files playing simultaneously. I need to prevent this. I think that the 'ended' event is relevant but, despite looking some examples, I can't see quite how to detect if a file is playing and wait until it's finished before allowing a second file to start (or even prevent it from playing at all). Any help would be much appreciated :)
Solution
You can add event listeners for the ended and playing events. Also, why creating a audio tag via javascript? I would just create an empty hidden audio tag:
<audio id='myAudio' autoplay='autoplay'></audio>
You have two options:
- disable/enable the button/link when audio is playing/stopped (preferred imho)
- ignore clicks when already playing
Then add two eventlisteners to it:
var playing = false;
$('#myAudio').on('playing', function() {
playing = true;
// disable button/link
});
$('#myAudio').on('ended', function() {
playing = false;
// enable button/link
});
$("p").click(function (event) {
if(!playing) {
var element = $(this);
var elementID = event.target.id;
var oggVar = (elementID +".ogg");
var audioElement = $('#myAudio')[0];
audioElement.setAttribute('src', oggVar);
audioElement.play();
}
});
Answered By - asgoth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.