Barbara
Barbara

Reputation: 14816

Javascript breaking audio players

I know about this issue in tumblr, the code gets stripped out and the audio players are broken.

I'm using flexslider.js now but the problem is pretty much the same. I fixed it with this

    setTimeout(function() {                        
                $('.audio').each(function(){
                    var audioID = $(this).parent().attr("id");
                    var $audioPost = $(this);
                    $.ajax({
                        url: '/api/read/json?id=' + audioID,
                        dataType: 'jsonp',
                        timeout: 50000,
                        success: function(data){
                            if ($audioPost.html().indexOf("is required to") != -1) {
                            $audioPost.append('<div style=\"background-color:black;">' + data.posts[0]['audio-player'] +'</div>');
                                }
                            }
                    });
                });
            }, 2000);

You need to resize your browser window to see this because I started coding from the mobile version, anyway...it looks ok on permalink pages http://tmbeta.tumblr.com/post/21264072020 but it doesn't when the photosets (which use flexslider) and the player are on the same page http://tmbeta.tumblr.com/

See how the player is added to the bottom of the post? I want it to appear where it says [Flash 9 is required to listen to audio.] instead. I know it's basically what .append does but I'm not familiar enough with jquery so I'm really struggling to find a solution.

Upvotes: 0

Views: 290

Answers (1)

kopischke
kopischke

Reputation: 3413

Looking at your HTML, the result is not surprising: you are scoping the append() to the element with the class audio, and that is the <article>. jQuery appends your new div to the end of that scope – which is the bottom of the article. You need to change the scope of your element insertion, either by

  1. Iterating over elements of class audio-player instead of audio, i.e.

    $('.audio-player').each(function(){ … }
    

    As this changes the scope of this, you will also have to adjust the line retrieving the post ID to look up the element hierarchy, i.e.

    var audioID = $(this).parents('.audio').attr('id');
    

    or by

  2. Scoping your element insertion to the player element proper, i.e.

    $audioPost.find('.audio-player').append('<div style=\"background-color:black;">' + data.posts[0]['audio-player'] +'</div>');
    

    If you’d rather replace the span inside that element instead of appending to it, so your player replaces the Flash warning, do

    $audioPost.find('#audio_player_'+audioID).replaceWith('<div style=\"background-color:black;">' + data.posts[0]['audio-player'] +'</div>');
    

    instead.

Answer edited after some trial and error on-site testing via chat; please ignore the comment thread.

Upvotes: 1

Related Questions