Get Youtube Related Videos using Youtube V3 API

This tutorial will explain how to get Youtube Related Videos using Youtube V3 API. YouTube will return related videos based on the youtube videoid. Also Youtube have given option for pagination and from this tutorial w3 Tweaks will explain how to achive YouTube pagination. So we can start our tutorial.

Getting Started with YouTube related videos using YouTube V3 API

Check before implementing this tutorial you have created your YouTube API Key one.Find Google console link to create YouTube API Key

Start with youtube pagination implementation

Below JavaScript will make click event to get Previous and Next page. Find the code below

$(document).ready(function() {
    youtubeApiCall();
    $("#pageTokenNext").on("click", function(event) {
        $("#pageToken").val($("#pageTokenNext").val());
        youtubeApiCall();
    });
    $("#pageTokenPrev").on("click", function(event) {
        $("#pageToken").val($("#pageTokenPrev").val());
        youtubeApiCall();
    });
});

Call YouTube releated video API using Jquery AJAX

Below JavaScript function will make ajax call to YouTube API. In this turorial youtube videoid is passed in url parameter(v=2gvreP74cuw). $(location).attr(‘href’).split(‘v=’)[1] code will get the youtube videoid from url parameter.

function youtubeApiCall() {
    var video = $(location).attr('href').split('v=')[1];
    $.ajax({
        cache: false,
        data: $.extend({
            key: 'API_KEY',
            relatedToVideoId: video,
            part: 'snippet',
            type: 'video'
        }, {
            maxResults: 20,
            pageToken: $("#pageToken").val()
        }),
        dataType: 'json',
        type: 'GET',
        timeout: 5000,
        url: 'https://www.googleapis.com/youtube/v3/search'
    }).done(function(data) {
        if (typeof data.prevPageToken === "undefined") {
            $("#pageTokenPrev").hide();
        } else {
            $("#pageTokenPrev").show();
        }
        if (typeof data.nextPageToken === "undefined") {
            $("#pageTokenNext").hide();
        } else {
            $("#pageTokenNext").show();
        }
        var items = data.items,
            videoList = "";
        $("#pageTokenNext").val(data.nextPageToken);
        $("#pageTokenPrev").val(data.prevPageToken);
        $.each(items, function(index, e) {
            videoList = videoList + '<li class="hyv-video-list-item"><div class="hyv-content-wrapper"><a href="?v=' + e.id.videoId + '" class="hyv-content-link" title="' + e.snippet.title + '"><span class="title">' + e.snippet.title + '</span><span class="stat attribution">by <span>' + e.snippet.channelTitle + '</span></span></a></div><div class="hyv-thumb-wrapper"><a href="?v=' + e.id.videoId + '" class="hyv-thumb-link"><span class="hyv-simple-thumb-wrap"><img alt="' + e.snippet.title + '" src="' + e.snippet.thumbnails.default.url + '" width="120" height="90"></span></a></div></li>';
        });
        $("#hyv-watch-related").html(videoList);
        // JSON Responce to display for user
        new PrettyJSON.view.Node({
            el: $(".hyv-watch-sidebar-body"),
            data: data
        });
    });
}

Note: Replace API_KEY with your youtube API key

YouTube will identify the previous and next page using “pageToken” parameter. So when ever YouTube API call made, youtube will pass “nextPageToken” and “prevPageToken“. Storing these parameters w3 Tweaks created two hidden input box with the id name. In above JavaScript function these two “$(“#pageTokenNext”).val(data.nextPageToken)” and “$(“#pageTokenPrev”).val(data.prevPageToken)” JavaScript code will store the values in the input box

HTML Code

<div class="row-fluid">
    <main id="content" role="main" class="span12">
        <!-- Begin Content -->
        <div id="hyv-page-container" style="clear:both;">
            <div class="hyv-content-alignment">
                <div id="hyv-page-content" class="" style="overflow:hidden;">
                    <div> <input type="hidden" id="pageToken" value="">
                        <div class="btn-group" role="group" aria-label="..."> <button type="button" id="pageTokenPrev" value="" class="btn btn-default">Prev</button> <button type="button" id="pageTokenNext" value="" class="btn btn-default">Next</button> </div>
                    </div>
                    <div id="hyv-watch-content" class="hyv-watch-main-col hyv-card hyv-card-has-padding">
                        <ul id="hyv-watch-related" class="hyv-video-list"> </ul>
                    </div>
                    <!-- Ads width 300px holder start -->
                    <div id="hyv-watch-sidebar-ads" style="float:left;">
                        <div id="hyv-watch-channel-brand-div" class="">
                            <div id="hyv-watch-channel-brand-div-text">Advertisement</div>
                            <div class="hyv-watch-sidebar-section">
                                <div style="font-weight:bold;height:10px;">JSON Responce</div>
                                <div class="hyv-watch-sidebar-body"></div>
                            </div>
                        </div>
                    </div>
                    <!-- Ads width 300px holder end -->
                </div>
            </div>
        </div>
    </main>
</div>

Download CSS

<link rel="stylesheet" href="https://www.w3tweaks.com/demo/youtube_related_videos/maincss.css" type="text/css">

Include Jquery Plugin

<script src="//code.jquery.com/jquery-2.1.4.js" type="text/javascript"></script>

Please like and share this article if you like this page. Do comment if you have any queries

Download Demo

Categories: ,
W3TWEAKS
Latest posts by W3TWEAKS (see all)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *