Playlist shortcode, prevent repeat

I was able to bind to the audio object’s ended event. But there is certainly more logic that would need to be added. This is working for me:

(function($){

    var customAudio = {

        initialize: function() {
            var self = this;
            // execute logic independently for each playlist in the document
            $('.wp-playlist').each(function(index) {
                // determine the last track in the playlist so that
                // when the last track ends we can pause the audio object
                lastTrack = $(this).find('.wp-playlist-tracks .wp-playlist-item:last a');
                // bind to the audio object's ended event and execute
                // our own ended logic
                $(this).find('audio').on('ended', function() {
                    // pass the audio object and the last track
                    self.ended(this, lastTrack);
                });
            });
        },

        ended : function (audio, lastTrack) {
            // if this audio element is the last track, pause it
            if ( audio.currentSrc === lastTrack.attr('href') ) {
                audio.pause();
            }
        }
    };

    $(function() {
        customAudio.initialize();
    });

}(jQuery));

Leave a Comment