nobe4
nobe4

Reputation: 2842

Audio event does not trigger jQuery on play event

I try to execute a function on an audio play event :

jQuery('audio').on('play', function () { /* ... */ });

But my element is not present at the time this function is executed, so it's not selected. Instead I have the habit to use a different syntax when I need to trigger event for dynamic added content :

jQuery('.constant-container').on('play', 'audio', function () {
    /* ... */ 
});

Where the .constant-container does not change. But this solution does not seems to work, the audio element does not get any click event either.

Here is a link to the bin.

The first 4 audio handle correctly the event, but not the 4 last.

Upvotes: 3

Views: 3342

Answers (1)

mido
mido

Reputation: 25034

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 play event,

jQuery.createEventCapturing(['play']);  
jQuery('body').on('play', 'audio', function(){... // now this would work.

JS Bin demo

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

    jQuery.createEventCapturing = (function () {
        var special = jQuery.event.special;
        return function (names) {
            if (!document.addEventListener) {
                return;
            }
            if (typeof names == 'string') {
                names = [names];
            }
            jQuery.each(names, function (i, name) {
                var handler = function (e) {
                    e = jQuery.event.fix(e);

                    return jQuery.event.dispatch.call(this, e);
                };
                special[name] = special[name] || {};
                if (special[name].setup || special[name].teardown) {
                    return;
                }
                jQuery.extend(special[name], {
                    setup: function () {
                        this.addEventListener(name, handler, true);
                    },
                    teardown: function () {
                        this.removeEventListener(name, handler, true);
                    }
                });
            });
        };
    })();

Upvotes: 4

Related Questions