XF 2.2 XF 2.2 java script issue on node page

SkyDrift

Member
I'm having a problem with Google API key and YouTube script not working on a node page or as widget in html box , they do work on other sites just fine but for xenforo 2.2 version they do not work for some reason.


JavaScript:
<script src="https://apis.google.com/js/platform.js"></script>

<script>
    // GET DATA
  var enjin_api = ' ';
    var enjin_url = ' ';
    var current_site = ' your site domain';
    var site_id = '1354982';
    var yt_api = ' your goggle Api key'
    var home_playlist = 'PL4FzBwuBtxhcpXNQGjharUX......l';
    var yt_normal ='1910318';
    var yt_featured = '1910319';
    var third_party_yt=['UCjBp_7RuDBUYbd1LegWEJ8g','UC-2Y8dQb0S6DtpxNgAKoJKA','UCKy1dAqELo0zrOtPkf0eTMw','UCXuqSBlHAE6Xw-yeJA0Tunw','UCcO-TjLkDNzvYrlPkOHgnfA','UCTeLqJq1mXUX5WWoNXLmOIA','UC2t5bjwHdUX4vM2g8TRDq5g','UCYAg4bYdyqENxEyHUX7t1FA','UCkWQ0gDrqOCarmUKmppD7GQ','UCeeFfhMcJa1kjtfZAGskOCA','UChIs72whgZI9w6d6FhwGGHA','UCfbi2EvzQmIJ55TJvZumNZw','UCey_c7U86mJGz1VJWH5CYPA','UCvWWf-LYjaujE50iYai8WgQ','UCftcLVz-jtPXoH3cWUUDwYw','UCRYOj4DmyxhBVrdvbsUwmAA'];
    var t_client = '0evb8pgxu4yrbi224hsxwl9pzt690k';
    var twitch_featured =1909194;
    var twitch_normal = 1909195;
    var third_party_featured = ['StarCitizen','xbox','playstation','ashesofcreation'];
    var third_party_streams=['linustech','ign','keencommunitynetwork','luke_lafr','Battlefield','machinima','eleaguetv','vrchallenger'];
    var game_streams = ['Star Citizen','Tera','Grand Theft Auto V','World of Warships','Black Desert Online','Fallout 4','The Witcher 3: Wild Hunt','Guild Wars 2','League of Legends','APB Reloaded','ArcheAge','Arma 3','Battlefield 1','Space Engineers','ashesofcreation'];
    
    var rss_feeds = [
        {
            url: ' https://www.pcgamer.com/rss/ ',
            name: 'PCGamer-Feeds'
        }
    ];
    var gallery_timer = 7;
    var gallery_array =[
            {
               image:"https://s3.amazonaws.com/files.enjin.com/1354982/gallery_images/BDO.jpg",
               title:"Play Black Desert!",
               description:"Join the Game",
               link:"https://www.blackdesertonline.com/",
               linktext:"Play Now",
               external:"yes"
           },
           {
               image:"https://s3.amazonaws.com/files.enjin.com/1354982/gallery_images/AoC_900x4xx.jpg",
               title:"Up Comming MMORPG Ashes Of Creation?",
               description:"THE NEXT GENERATION MMORPG",
               link:"https://www.ashesofcreation.com/ref/SkyDrifter/?campaign=C-Comms(ControlledCommunications)",
               linktext:"Register Now",
               external:"yes"
           },           
            {
               image:"https://s3.amazonaws.com/files.enjin.com/1354982/gallery_images/star_citizen.jpg",
               title:"Join Up Star Citizen!",
               description:"Introduce yourself in our forums",
               link:"/forums/m/42039322/viewthread/29591305-introduce-yourself",
               linktext:"Forums",
               external:""
           },

           {
               image:"https://s3.amazonaws.com/files.enjin.com/1354982/gallery_images/conan_exiles.jpg",
               title:"Conan Exiles?",
               description:"Discuss Servers in the forums",
               link:"/forums/m/42039322/viewforum/8015115",
               linktext:"Forums",
               external:""
           },

           {
               image:"https://s3.amazonaws.com/files.enjin.com/1354982/gallery_images/ark-banner.jpg",
               title:"Ark Survival Evoled",
               description:"Discuss Servers in the forums",
               link:"/forums/m/42039322/viewforum/8015115",
               linktext:"Forums",
               external:"no"
           }
          
    ];

</script>
<script>
    // YouTube Channels
function get_users(tag_id, user_group) {
    if (tag_id == "tparty") {
        $.each(third_party_yt, function(i, youtube) {
        $.get(
            "https://www.googleapis.com/youtube/v3/channels", {
                part: "snippet",
                id: youtube,
                key: yt_api,
            },
            function(data) {
                var avatar = data.items[0].snippet.thumbnails.high.url;
                var username = data.items[0].snippet.title;
                $('#' + user_group).append('<a class="user_block" data-id="' + youtube + '" data-username="' + username + '" ><div class="user_inner"><div class="image_wrap"><img src="' + avatar + '"></div><div class="username">' + username + '</div></div></a>').delay(300).queue(function(next) {
                    $('.user_block[data-id="' + youtube + '"]').addClass('animated fadeIn');
                    next();
                });
                $.get(
                    "https://www.googleapis.com/youtube/v3/channels", {
                        part: "contentDetails",
                        id: youtube,
                        key: yt_api,
                    },
                    function(data) {
                        var playlist = data.items[0].contentDetails.relatedPlaylists.uploads
                        $('.user_section a[data-id="' + youtube + '"]').attr('data-playlist', playlist);
                        user_click('.user_section a[data-id="' + youtube + '"]');
                    });

            });
        });
    }
    else{
    var user_list = {
        "jsonrpc": "2.0",
        "id": Math.round(Math.random() * (999999 - 100000) + 100000),
        "method": "UserAdmin.get",
        "params": {
            "api_key": enjin_api,
            "tag_id": tag_id
        }
    };
    $.post(enjin_url, JSON.stringify(user_list), function(response) {
        var data = response.result;
        var array_length = Object.keys(data).length;
        var counter = 0;
        if (response.error) {
            console.log(response.error.message);
        } else {

            $.each(data, function(user_id, value) {
                var username = value.username;

                var user_data = {
                    "jsonrpc": "2.0",
                    "id": Math.round(Math.random() * (999999 - 100000) + 100000),
                    "method": "Profile.getInfo",
                    "params": {
                        "user_id": user_id,
                    }
                };


                $.post(enjin_url, JSON.stringify(user_data), function(response) {
                    if (response.error) {
                        console.log(response.error.message);
                    } else {
                        var data = response.result;
                        var location = data.location;
                        var location_name = data.location_name;
                        var friends = data.friends;
                        var steam = data.gamerid_steam;
                        var psn = data.gamerid_psn;
                        var xbox = data.gamerid_xbox;
                        var twitter = data.gamerid_twitter;
                        var facebook = data.gamerid_facebook;
                        var youtube = data.gamerid_youtube;
                        var twitch = data.gamerid_twitch;
                        var bio = data.about;
                        var profile_name = data.username;




                        if (youtube != '') {

                            $.get(
                                "https://www.googleapis.com/youtube/v3/channels", {
                                    part: "snippet",
                                    id: youtube,
                                    key: yt_api,
                                },
                                function(data) {
                                    var avatar = data.items[0].snippet.thumbnails.high.url;
                                    var username = data.items[0].snippet.title;
                                    $('#' + user_group).append('<a class="user_block" data-id="' + youtube + '" data-username="' + username + '" data-enjin_id="' + user_id + '"><div class="user_inner"><div class="image_wrap"><img src="' + avatar + '"></div><div class="username">' + username + '</div></div></a>').delay(300).queue(function(next) {
                                        $('.user_block[data-id="' + youtube + '"]').addClass('animated fadeIn');
                                        next();
                                    });
                                    $.get(
                                        "https://www.googleapis.com/youtube/v3/channels", {
                                            part: "contentDetails",
                                            id: youtube,
                                            key: yt_api,
                                        },
                                        function(data) {
                                            var playlist = data.items[0].contentDetails.relatedPlaylists.uploads
                                            $('.user_section a[data-id="' + youtube + '"]').attr('data-playlist', playlist);
                                            user_click('.user_section a[data-id="' + youtube + '"]');
                                        });

                                });
                        }
                    }
                });
            });
        }
    });
}
} // End Get Users

function back_menu(){

    
    $('.video_content.active').removeClass('fadeIn').delay(300).queue(function(next){
        $('.video_content.active').removeClass('active');
        next();
    });
    $('.user_display').removeClass('fadeOut').delay(300).queue(function(next){
        $('.user_display').removeClass('inactive');
        next();
    });
    $('.player_display').html('<div class="default_display"> Pick a member to watch their videos</div>');
    
}

function user_click(target) {
    $(target).click(function() {
        $('.user_display').addClass('fadeOut').delay(300).queue(function(next){
            $('.user_display').addClass('inactive');
            next();
        });
        if ($('.default_display').length) {
            $('.player_display').html('<div class="player_area"> <div class="tv"></div> <div class="tv_info"></div> </div>');
        }
        var user_id = $(target).attr('data-id');
        var playlist = $(target).attr('data-playlist');
        var username = $(target).attr('data-username');


        if ($('.video_content[data-user="' + user_id + '"]').length) {
            var video_id = $('.video_content[data-user="' + user_id + '"] .vid_col[data-marker="1"]').attr('data-id');
            $('.video_content').removeClass('active');
            $('.video_content[data-user="' + user_id + '"]').addClass('active');
            $('.vid_col').removeClass('active_play');
            $('.vid_col[data-id="'+video_id+'"]').addClass('active_play');
            $('.tv').html('<iframe width="560" height="315" src="//www.youtube.com/embed/' + video_id + '?theme=light&showinfo=0&rel=0&autohide=1&color=white" frameborder="0" allowfullscreen></iframe>');
        } else {
            $('.video_content').removeClass('active');
            $('.video_page .user_videos').prepend('<div class="video_content active" data-user="' + user_id + '"><div class="vid_nav"><a class="back_menu" href="#" onclick="event.preventDefault(); back_menu(this);">Back to Users </a> <i class="fa fa-angle-right"></i> <div class="nav_title">' + username + '\'s Videos</div></div><div class="vid_list"></div></div>');
            
            
            var video_ids = [""];

            $.get(
                "https://www.googleapis.com/youtube/v3/playlistItems", {
                    part: 'contentDetails',
                    maxResults: 10,
                    playlistId: playlist,
                    key: yt_api
                },
                function(data) {
                    $.each(data.items, function(i, item) {
                        var marker = parseInt(i) + 1;

                        var video_id = (item.contentDetails.videoId);
                        video_ids.push(item.contentDetails.videoId);
                        $('.video_content[data-user="' + user_id + '"] .vid_list').append('<div class="vid_col" data-id="' + video_id + '" data-order="' + i + '" data-marker="' + marker + '"></div>');

                    });

                }).done(function() {

                video_ids.forEach(function(video_id) {
                    $.get(
                        "https://www.googleapis.com/youtube/v3/videos", {
                            part: 'statistics,snippet,contentDetails',
                            id: video_id,
                            key: yt_api
                        },
                        function(data) {
                            $.each(data.items, function(i, item) {

                                var id = item.id;
                                //Statistics
                                var views = item.statistics.viewCount;
                                var likes = item.statistics.likeCount;
                                var comments = item.statistics.commentCount;
                                //Snippet
                                var thumbnail = item.snippet.thumbnails.high.url;
                                var title = item.snippet.title;
                                var description = item.snippet.description;
                                var author = item.snippet.channelTitle;
                                var raw_date = item.snippet.publishedAt;
                                var date = item.snippet.publishedAt;
                                var channel_id = item.snippet.channelId;
                                var duration = item.contentDetails.duration;
                                var formattedDuration = duration.replace("PT", "").replace("H", ":").replace("M", ":").replace("S", "");
                                var timeStr = (date);
                                var date = new Date(timeStr);
                                var day = date.getDate();
                                var year = date.getFullYear();
                                var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
                                var month_num = date.getMonth();
                                var month = months[month_num];
                                var dateStr = month + ' ' + day + ', ' + year;
                                var channel_id = item.snippet.channelId;
                                var marker = parseInt($('.video_content[data-user="' + user_id + '"] .vid_list .vid_col[data-id="' + id + '"]').attr('data-order')) + 1;
                                $('.video_content[data-user="' + user_id + '"] .vid_list .vid_col[data-id="' + id + '"]').attr('data-channel', channel_id);
                                $('.video_content[data-user="' + user_id + '"] .vid_list .vid_col[data-id="' + id + '"]').attr('data-title', title);
                                $('.video_content[data-user="' + user_id + '"] .vid_list .vid_col[data-id="' + id + '"]').attr('data-description', description);
                                $('.video_content[data-user="' + user_id + '"] .vid_list .vid_col[data-id="' + id + '"]').attr('data-author', author);
                                $('.video_content[data-user="' + user_id + '"] .vid_list .vid_col[data-id="' + id + '"]').append('<div class="video_block " data-date="' + raw_date + '" onclick="video_controls(this);"><div class="list_content"><a data-link="https://www.youtube.com/watch?v=' + id + '" data-title="' + title + '" class="clearfix video_link"><div class="marker">' + marker + '</div><img class="video_thumb" src="' + thumbnail + '" alt="' + title + '"></img><div class="video_info clearfix"><div class="video_title">' + title + '</div><div class="video_author">' + author + '</div></div></a></div>');
                                if (marker == 1) {

                                    $('.video_content[data-user="' + user_id + '"] .vid_list .vid_col[data-id="' + id + '"] .marker').html('<i class="fa fa-play"></i>');
                                    $('.vid_col').removeClass('active_play');
            $('.vid_col[data-id="'+id+'"]').addClass('active_play');
                                    $('.tv').html('<iframe width="560" height="315" src="//www.youtube.com/embed/' + id + '?theme=light&showinfo=0&rel=0&autohide=1&color=white" frameborder="0" allowfullscreen></iframe>');
                                    $('.tv_info').html('<h1>' + title + '</h1><div class="subscribe_block"><div class="g-ytsubscribe" data-channelid="' + channel_id + '" data-layout="full" data-count="default" ></div></div><h3 class="description_toggle">Show Description</h3><span class="main_description animated fadeIn">' + description + '</span>');

                                    gapi.ytsubscribe.go('.g-ytsubscribe');

                                    $('.description_toggle').click(function() {
                                        if ($(this).text() == 'Show Description') {
                                            $(this).parent().find(".main_description").addClass('fadeIn display_desc').removeClass('fadeOut');
                                            $(this).text('Hide Description');
                                        } else {
                                            $(this).text('Show Description');
                                            $(this).parent().find(".main_description").removeClass('fadeIn display_desc');
                                        }
                                    });


                                }


                                $('.video_content[data-user="' + user_id + '"] .vid_column').addClass('animated fadeIn');
                            });
                        });
                }); // End statistics each


            }); // End done
            //clear array at end,  avoids duplicates on next run
            var video_ids = [];

        }

        window.scrollTo(0, 0);
    });

}


function video_controls(target) {

        if ($(target).find('.marker i').length) {

        } else {
            $('.vid_col').removeClass('active_play');
            var current_play = $('.vid_col .marker i').parents('.vid_col').attr('data-marker');
            $('.vid_col .marker i').parents('.marker').html(current_play);
            $(target).parent('.vid_col').find('.marker').html('<i class="fa fa-play"></i>');
            $(target).parent('.vid_col').addClass('active_play');
            var video_link = $(target).parent('.vid_col').attr("data-id");
            var video_title = $(target).parent('.vid_col').attr("data-title");
            var video_description = $(target).parent('.vid_col').attr("data-description");
            var video_author = $(target).parents('.vid_col').attr("data-author");
            var channel = $(target).parents('.vid_col').attr("data-channel");



            $('.tv').html('<iframe width="560" height="315" src="//www.youtube.com/embed/' + video_link + '?theme=light&showinfo=0&rel=0&autohide=1&color=white" frameborder="0" allowfullscreen></iframe>');

            $('.tv_info h1').html(video_title);
            $('.main_description').html(video_description);
            $('.vid_list').removeClass('active');
            window.scrollTo(0, 0);

        }



}



$(document).ready(function() {
    get_users(yt_featured, "featured");
    get_users(yt_normal, "standard");
    get_users("tparty","tparty");

});
</script>
 

Mike

XenForo developer
Staff member
I replied to your ticket, but the fundamental issue is that your code relies on jQuery and it's being called before XF has loaded jQuery.
 

SkyDrift

Member
I found the problem as I forgot Xenforo didn't have JQ loaded so I had to put the external link to it in code always something so simple we forget to do 🤯
JavaScript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
 
Top