I'd like to log when users listen to an audio element for more than 5 seconds. How can I detect this with HTML5?
I would handle the play event, and then use a setTimeout call track when they're done. Something like this (pseudo code):
var timeHandler = null;
// if they stop listening, don't give them the alert
myAudioElement.addEventListener('stop', function() {
if (timeHandler) clearTimeout(timeHandle);
});
// when they start to play, set an event to pop up 5 seconds later
myAudioElement.addEventListener('play', function() {
timeHandler = setTimeout(5000,function() {
// here I would make some kind of ajax call to log the event
alert("it's been 5 seconds!");
});
As always, this could get far more complex depending upon your needs. You could also just use the ontimeupdate event to track where the playhead is currently sitting. For a reference on html5 audio events, check out this page:
https://developer.mozilla.org/en/DOM/Media_events
Good luck!
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