6

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

j0h4nn3s
  • 2,016
  • 2
  • 20
  • 35
  • Looks like the easiest solution would be to declare the event handler after having dynamically added the audio. You can merely detect `timeupdate` on `audio` or `video` (so not on `body`) and `.on('load'` doesn't lend itself for a delegated event, in order to detect when the new audio has loaded. Or just possibly a custom event could be created : http://stackoverflow.com/a/11886423/3168107. – Shikkediel Apr 15 '15 at 18:58

1 Answers1

5

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);
        }
      });
    });
  };
})();
Community
  • 1
  • 1
mido
  • 24,198
  • 15
  • 92
  • 117
  • I got this error: "Uncaught TypeError: ((jQuery.event.special[handleObj.origType] || (intermediate value)).handle || handleObj.handler).apply is not a function" – Snickbrack Jan 18 '16 at 15:05