Search code examples
jqueryajaxjplayer

jplayer.org save playlist in cookies


I have a working Jplayer and I'm proud to share it here for everyone's convenience.

It memorizes the playlist in a cookie as I add single tracks inside it. Here's the working code:

// PLAY SINGLE SONG
// el delegation is needed because songs are dynamically loaded via ajax datatables
$(document).on("click", '.playable', function(el) {
    var title = $(this).data("title");
    var artist = $(this).data("artist");
    var mp3 = $(this).data("mp3");
    var poster = $(this).data("poster");
    myPlaylist.add({
        title: title,
        artist: artist,
        mp3: mp3,
        poster: poster
    }, true ); /* true makes it play on load */
});

The cookie storage is triggered here, using a standard jplayer function:

$("#jquery_jplayer").bind($.jPlayer.event.play, function(el) {
    Cookies.remove('jp_playlist');
    Cookies.set('jp_playlist', JSON.stringify(myPlaylist) );
});

But I also have a button ADD ALL, which maps each song and adds it to the playlist:

// PLAY ALL
$(document).on("click", '#play_all', function(el) {

    // play all
    $.map($('.playable'), function(el) {
        var title = $(el).data("title");
        var artist = $(el).data("artist");
        var mp3 = $(el).data("mp3");
        var poster = $(el).data("poster");
        myPlaylist.add({
            title: title,
            artist: artist,
            mp3: mp3,
            poster: poster
        });
    });

    var current = myPlaylist.current;
    myPlaylist.play(current); /* if I would have put "true" like above it would have started the last song instead of the first */

    Cookies.remove('jp_playlist');
    Cookies.set('jp_playlist', JSON.stringify(myPlaylist) );
});

The cookie is not set and the playlist isn't retained upon page reload. I alert( JSON.stringify(myPlaylist) ) and everything shows fine. It seems that either myPlaylist.play(current) doesn't trigger the bind($.jPlayer.event.play) and my last 2 lines which force the cookie storage don't work. I also tried to remove that lines and put the "true", to test if it triggers the bind.event.play but it doesn't work.

Thank you in advance for your time and any hint.


Solution

  • It was a cookies storage limit. I simply bypassed the limit using localstorage, e.g.:

    localStorage.setItem('jp_playlist', JSON.stringify(myPlaylist) );
    localStorage.removeItem('jp_playlist');
    

    instead of

    Cookies.set('jp_playlist', JSON.stringify(myPlaylist) );
    Cookies.remove('jp_playlist');