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 :)
Audio pause() Method The pause() method halts (pauses) the currently playing audio. Tip: This method is often used together with the play() method. Tip: Use the controls property to display audio controls (like play, pause, seeking, volume, etc, attached on the audio).
The Audio tag has a paused property. If it is not paused, then it's playing.
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:
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With