Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 audio bind timeupdate before element exists

im trying to bind the "timeupdate" event from an audio tag, which doesn't exist yet. I was used to do it this way:

$("body").on("click","#selector", function(e) {

});

I tried this with the audio tag:

$("body").on("timeupdate", ".audioPlayerJS audio", function(e) {
    alert("test");
    console.log($(".audioPlayerJS audio").prop("currentTime"));
    $(".audioPlayerJS span.current-time").html($(".audioPlayerJS audio").prop("currentTime"));
});

This doesn't work though. Is this supposed to work? Or what am I doing wrong?

Any help is highly appreciated.

There is a fiddel for you: jsfiddel

like image 925
j0h4nn3s Avatar asked Apr 15 '15 18:04

j0h4nn3s


1 Answers

Apparently media events( those specifically belonging to audio or video like play, pause, timeupdate, etc) do not get bubbled. you can find the explanation for that in the answer to this question.

So using their solution, I captured the timeupdate event,

$.createEventCapturing(['timeupdate']);  
$('body').on('timeupdate', '.audioPlayerJS audio', updateTime); // now this would work.

JSFiddle demo

the code for event capturing( taken from the other SO answer):

$.createEventCapturing = (function () {
  var special = $.event.special;
  return function (names) {
    if (!document.addEventListener) {
      return;
    }
    if (typeof names == 'string') {
      names = [names];
    }
    $.each(names, function (i, name) {
      var handler = function (e) {
        e = $.event.fix(e);
        return $.event.dispatch.call(this, e);
      };
      special[name] = special[name] || {};
      if (special[name].setup || special[name].teardown) {
        return;
      }
      $.extend(special[name], {
        setup: function () {
          this.addEventListener(name, handler, true);
        },
        teardown: function () {
          this.removeEventListener(name, handler, true);
        }
      });
    });
  };
})();
like image 129
mido Avatar answered Oct 13 '22 23:10

mido