Audio Playlist : How to bind events for “track change”, “track end”?

I’m customizing native WordPress playlist

echo do_shortcode('');

I’d like to bind events to detect “track change” and “track end” and do something when those events fired.

So, I checked wp-playlist.js. I see some events but I have no idea how to bind it on a separate js file (jquery)

events : {
        'click .wp-playlist-item' : 'clickTrack',
        'click .wp-playlist-next' : 'next',
        'click .wp-playlist-prev' : 'prev'
    },

    clickTrack : function (e) {
        e.preventDefault();

        this.index = this.$( '.wp-playlist-item' ).index( e.currentTarget );
        this.setCurrent();
    },

    ended : function () {
        if ( this.index + 1 < this.tracks.length ) {
            this.next();
        } else {
            this.index = 0;
            this.current = this.tracks.at( this.index );
            this.loadCurrent();
        }
    },

    next : function () {
        this.index = this.index + 1 >= this.tracks.length ? 0 : this.index + 1;
        this.setCurrent();
    },

    prev : function () {
        this.index = this.index - 1 < 0 ? this.tracks.length - 1 : this.index - 1;
        this.setCurrent();
    },

Is it possible to bind those events?

1 Answer
1

You can bind to the ‘ended’ event by targeting the audio element in the playlist:

$('.wp-playlist .mejs-mediaelement audio').on('ended', function (event) {
    console.log('ended');
});

The ‘click’ events are just standard, eg:

$('.wp-playlist-item').on('click', function (event) {
    console.log('clicked');
});

Leave a Comment