Build a Youtube Video Search in Javascript With Pagination Using Youtube Data API V3 Full Project

Build a Youtube Video Search in Javascript With Pagination Using Youtube Data API V3 Full Project

Welcome folks today in this blog post we will be discussing about how to make a advanced video search in youtube with pagination using the youtube data api v3. All the source code of the application is given below and also to download. A step by step youtube video is also shown below to follow with the blog.

 

 

Screenshots

 

 

 

 

Source Code

 

<!DOCTYPE html>
<html>
  <head>
    <title>Youtube Video Advanced Search App in Javascript</title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
  </head>
  <body>
  <div class="container">
      <br>
      <h1 class="text-center">
          Youtube Advanced Search App
      </h1>
      <br>
      <form id="myForm" autocomplete="off">
          <div class="form-group">
            <input class="form-control" type="text" id="search" placeholder="Topic" required>
          </div>
          <div class="form-group">
            <label for="duration">Select Duration:</label>
            <select class="form-control" id="duration">
              <option>any</option>
              <option>short</option>
              <option>medium</option>
              <option>long</option>
            </select>
          </div>
          <div class="form-group">
            <label for="order">Order:</label>
            <select class="form-control" id="order">
              <option>relevance</option>
              <option>viewCount</option>
              <option>videoCount</option>
              <option>title</option>
              <option>rating</option>
              <option>date</option>
            </select>
          </div>
          <div class="form-group">
              <label for="fromdate">Before:</label>
              <input type="text" class="form-control" name="" id="beforedate">
          </div>
          <div class="form-group">
            <label for="fromdate">After:</label>
            <input type="text" class="form-control" name="" id="afterdate">
        </div>
          <div class="form-group">
              <button id="btn" class="btn btn-danger btn-block">
                  Search Videos
              </button>
          </div>
      </form>
      <table style="display: none;" id="table" class="table table-striped">
        <thead>
          <tr>
            <th>Title</th>
            <th>Thumbnail</th>
            <th>Visit Channel</th>
          </tr>
        </thead>
        <tbody id="results">
        </tbody>
      </table>
      <div id="pager">
		<ul id="pagination" class="pagination-sm"></ul>
	</div>
  </div>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.4.4/umd/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
  <script src="jquery.twbsPagination.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
  <script>
      $("#beforedate").datepicker({

      })
      $("#afterdate").datepicker({

})

  </script>
  <script src="script.js"></script>
</html>

 

$(document).ready(function () {
  var $pagination = $("#pagination"),
    totalRecords = 0,
    records = [],
    recPerPage = 0,
    nextPageToken = "",
    totalPages = 0;
  var API_KEY = "";
  var search = "";
  var duration = "any";
  var order = "relevance";
  var beforedate = new Date().toISOString();
  var afterdate = new Date().toISOString();
  var maxResults=10

  $("#beforedate").val(beforedate)
  $("#afterdate").val(afterdate)

  $("#beforedate").change(function(){
      beforedate = new Date(this.val()).toISOString()
      $("#beforedate").val(beforedate)
      afterdate = new Date(this.val()).toISOString()
      $("#afterdate").val(afterdate)
  })

  $("#afterdate").change(function(){
    afterdate = new Date(this.val()).toISOString()
    $("#afterdate").val(afterdate)
    beforedate = new Date(this.val()).toISOString()
    $("#beforedate").val(beforedate)
})

  $("#duration").change(function () {
    duration = $(this).children("option:selected").val();
  });
  $("#order").change(function () {
    order = $(this).children("option:selected").val();
  });

  $("#myForm").submit(function (e) {
    e.preventDefault();

    search = $("#search").val();

    //beforedate = new Date($("#beforedate").val()).toISOString();

    //afterdate = new Date($("#beforedate").val()).toISOString();

    console.log(beforedate);

    API_KEY = "######YOURAPIKEY############";

    var url = `https://www.googleapis.com/youtube/v3/search?key=${API_KEY}
        &part=snippet&q=${search}&maxResults=${maxResults}&publishedAfter=${afterdate}&publishedBefore=${beforedate}&order=${order}&videoDuration=${duration}&type=video`;

    $.ajax({
      method: "GET",
      url: url,
      beforeSend: function () {
        $("#btn").attr("disabled", true);
        $("#results").empty();
      },
      success: function (data) {
        console.log(data);
        $("#btn").attr("disabled", false);
        displayVideos(data);
      },
    });
  });

  function apply_pagination() {
    $pagination.twbsPagination({
      totalPages: totalPages,
      visiblePages: 6,
      onPageClick: function (event, page) {
        console.log(event);
        displayRecordsIndex = Math.max(page - 1, 0) * recPerPage;
        endRec = displayRecordsIndex + recPerPage;
        console.log(displayRecordsIndex + "ssssssssss" + endRec);
        displayRecords = records.slice(displayRecordsIndex, endRec);
        generateRecords(recPerPage, nextPageToken);
      },
    });
  }

  $("#search").change(function () {
    search = $("#search").val();
  });

  function generateRecords(recPerPage, nextPageToken) {
    var url2 = `https://www.googleapis.com/youtube/v3/search?key=${API_KEY}
    &part=snippet&q=${search}&maxResults=${maxResults}&pageToken=${nextPageToken}&publishedBefore=${beforedate}&publishedAfter=${afterdate}&order=${order}&videoDuration=${duration}&type=video`;

    $.ajax({
      method: "GET",
      url: url2,
      beforeSend: function () {
        $("#btn").attr("disabled", true);
        $("#results").empty();
      },
      success: function (data) {
        console.log(data);
        $("#btn").attr("disabled", false);
        displayVideos(data);
      },
    });
  }

  function displayVideos(data) {
    recPerPage = data.pageInfo.resultsPerPage;
    nextPageToken = data.nextPageToken;
    console.log(records);
    totalRecords = data.pageInfo.totalResults;
    totalPages = Math.ceil(totalRecords / recPerPage);
    apply_pagination();
    $("#search").val("");

    var videoData = "";

    $("#table").show();

    data.items.forEach((item) => {
      videoData = `
                    
                    <tr>
                    <td>
                    <a target="_blank" href="https://www.youtube.com/watch?v=${item.id.videoId}">
                    ${item.snippet.title}</td>
                    <td>
                    <img width="200" height="200" src="${item.snippet.thumbnails.high.url}"/>
                    </td>
                    <td>
                    <a target="_blank" href="https://www.youtube.com/channel/${item.snippet.channelId}">${item.snippet.channelTitle}</a>
                    </td>
                    </tr>

                    `;

      $("#results").append(videoData);
    });
  }
});

 

See also  How to Automate Omegle in Javascript | Build a Simple Omegle Bot in Javascript Full Project

DOWNLOAD SOURCE CODE

Leave a Reply