Coding is fun when it is pushed with the lubricants of Design to bring out the best program. Pick your coding language and start learning now. It is never too late. I have no experience in coding but the passion to learn something and utilize it in my daily office work pushes me hard to do something new each day.
if (youWant() == true) {
youCan()
} else {
youCan’t()
}
What are we doing?
We are making a YouTube PlayList App using the YouTube API. We will extract some data from the YouTube Playlist page of your choice and then display the result in our Web App.
You will find end number of tutorials on the internet but when a Designer (a non-coder) is taking an online tutorial class from a coder — somethings are surely going to bounce over the head. No matter how simplistically that tutorial is explained.
I am going to attempt the same but from a Designer’s point of view, who has somewhat read about the variables, objects, functions or methods of JavaScript but can’t decipher the program. So let’s start:
How do we extract data from YouTube?
Through a Google API key, playlistId and URL.
How should we start?
We first have to make an HTML page where we will display our app content. We would need a logo to show in the header, main video and then thumbnails of next videos in a list with Titles and a short brief (intro) of two lines. I won’t be covering the HTML/CSS of this program in detail, as its all about it’s coding in JQuery. Assuming that you know HTML/CSS let’s start designing the page.
- For Header: Make a container <div> and then put a logo image in the <header>.
- Main Video Section: Make a <section> with id=video and paste the embed video code (<iframe>) that you can easily get from youtube video share option, with the default width i.e. 560px.
- Video List Section: Below the main video — create a <main> section with image, and <div> inside the <article>.
- <img> should carry a class “thumb”.
- <div> will consist of a class name “details”, title for <h4></h4> and <p></p> for short brief. You can write a dummy title and a short brief for now, just to check how the title and intro is looking in HTML.
We are not covering CSS here as to each its own. You can use formatting, colors, spacing as per your preferences and beautify it accordingly. Our HTML page completes here.
Preparation before start coding
We have to collect all the required information to code this program, so without wasting a time let’s collect some information before we dive into actual coding:
- Visit List of PlaylistItems of YouTube API from Google Docs website. You can pull in any information from YouTube API like channels, captions, comments etc. Since we are making just a playlist, we will focus on that for now. In PlaylistItems-List, click on Javascript tab in Usage, where you see some predefined parameters (playlistId, maxResults, part) and HTTP Request URL (Get https://www.googleapis.com/youtube/v3/playlists) down below.
- PlaylistId sends the request to Google YouTube API to fetch information. We need to make our program YouTube API enabled, and for that we need to know the API key. Keep this browser tab opened for now.
- Open developer console of Google in a different tab of the browser, make a new project, give your project a name and click Create. It will take few seconds to create depending on your internet speed. Finally, when it is created, open it and then enable APIs & Services. (Image for reference).
- Now Search for YouTube Data API v3 which consists of YouTube data for videos, playlists, captions, titles, etc. Once you find YouTube Data API v3, click and enable it. We now need the API key, which is actually our password to fetch YouTube data. Go to Credentials on the left nav panel and click API Key in create credentials as shown in the figure.
- Copy the API key you just created and save it somewhere.
Deep dive into coding
This section covers jQuery. Now you have all the resources required to build your own YouTube Playlist app. I will try to explain every line of code and then present the actual code at the end. And for those who can code and not interested in reading the explanation part of this program, can jump directly to the last section of this article to download the code.
Section — (i)
Let’s start with the program
Hey jQuery when the document is ready, I want you to do something. $ symbol is basically used for jQuery. The following line of code is not closed (}) as we are going to write the whole program inside it.
CODE:
$(document).ready(function() {
What next?
- Declare variables of key, playlistId, URL and save their values in it.
- API key is what we got from the credentials of YouTube Data API v3, which we saved earlier.
- Playlist id can be discovered from the YouTube playlist web address (image for reference).
- URL is the same, which was there in Playlistitems: list/request.
CODE:
var key = ‘AIzaSyAggZgfVPF-A_zwqI8IzSTbKJaI8iGCKZQ’;
var playlistId = ‘PLZwJxqUEreM__Gie32F2Pn0ZTxrbibrF6’;
var URL = ‘https://www.googleapis.com/youtube/v3/playlistItems';
Section — (ii)
What next?
Create an array of object (‘options’) for all the parameters required to execute the request, which will eventually generate the API response.
- Snippet carries the thumbnails, title, id, description data so we will use only that (image for reference).
- You can put as many results you want to show. We are using 15.
- We just saved the playlistId above, now save that in this object.
CODE:
var options = {
part: ‘snippet’,
key: key,
maxResults: 15, //you can use as many
playlistId: playlistId
}
Section — (iii)
What next?
Now we have to beef up the HTML with videos by sending a request to YouTube API to ‘loadvideos’ and for that, we need to make a function, where the URL will pass options to get raw ‘data’ in JSON form.
CODE:
loadVids();
function loadVids() {
$.getJSON(URL, options, function(data){
What next?
After the request is made to loadVideos it should find the video id of the first item from the playList array and store it in variable ‘id’ (refer image above).
CODE:
var id = data.items[0].snippet.resourceId.videoId;
Section — (iv)
What next?
We will call the main video from its function (mentioned next), which will take the variable ‘id’ from the very first video of the Playlist and load it in the HTML.
CODE:
mainVid(id);
What next?
Once the HTML is injected with the new id we will call the function ‘listLoop’ defined below.
CODE:
listLoop(data);
});
}
What next?
Now we tell jQuery ($) to find out something called #video in our HTML page. Cut that whole <iframe></iframe> from it and paste it here within back texts (`` not quotes). Back text (``) allows us to inject variables directly into the string. The advantage of using back text is that spaces and line breaks are not affected in the line of codes.
CODE:
function mainVid(id) {
$(‘#video’).html(`
<iframe width=”560" height=”315" src=”https://www.youtube.com/embed/m7--wmb8LN4" frameborder=”0" allow=”autoplay; encrypted-media” allowfullscreen></iframe>
`);
}
What next?
Now we call the ‘listLoop’ function to throw in data that API called, and for each item, we create variables as per their object path as shown in the image above.
CODE:
Function listLoop(data) {
What next?
- Listen jQuery, for each of the data in items array, we want you to make a function and pass items as per their indexes in the array (‘i’) in ‘item’.
- Make variables for items that will be displayed under listLoop (thumbnails, title, description, video id) and then save the values of their object path.
- Limit characters word count that will come in the description to 100 starting from 0 otherwise it will take exactly the same word count of video uploaded on YouTube and it will look bad.
CODE:
$.each(data.items, function(i, item) {
var thumb = item.snippet.thumbnails.medium.url;
var title = item.snippet.title;
var desc = item.snippet.description.substring(0, 100);
var vid = item.snippet.resourceId.videoId;
What next?
Now let’s push (#main) content, which is finally going to display the article (content) from jQuery, so:
- Hey jQuery select the main container in HTML
- Cut the whole <article> tag from the HTML and paste it here in the code.
- Close
CODE:
$(‘main’).html(`
<article><img src=”https://cdn.pixabay.com/photo/2018/06/05/10/56/railway-tracks-3455169__480.jpg" alt=”” class=”thumb”>
<div class=”details”>
<h4>title</h4>
<p>desc</p>
</div></article>
`)
});
}
Revisit the above chunk of code:
Above written code will only change the content of the last video in the list (item[14]) and display it. So only one video will be displayed under the main video list, whereas we want to show all fifteen videos (maxResults: 15). We have to make the above code dynamic now to display video id, thumb, title, desc dynamically, so:
- Hey jQuery select the main container in HTML and ‘append’ so that all fifteen videos can be displayed.
- Add a class ‘item’ and call the variable ‘vid’ (saved earlier) in data-key to inject the listLoop to play mainVideo when it is clicked.
- Inject listLoop variables in image source, <h4> and <p> to make them dynamic
- Close
CODE REVISITED:
$(‘main’).append(`
<article class=”item” data-key=”${vid}”>
<img src=”${thumb}” alt=”” class=”thumb”>
<div class=”details”>
<h4>${title}</h4>
<p>${desc}</p>
</div>
</article>
`)
});
}
Section — (v)
What next?
When we click on any video in the listLoop, we want the main video to change and run the same, so:
- Hey jQuery when the ‘main’ is clicked, look for the ‘article’ element, which has all the information we want.
- Pull out ‘this’ clicked video, which is stored in the data-key of the article.
- Create a new variable ‘id’, which will select ‘this’ element called ‘data-key’.
- Lastly, call the main video whenever the article is clicked in the video list with its new variable ‘id’.
CODE:
$(‘main’).on(‘click’, ‘article’, function() {
var id = $(this).attr(‘data-key’);
mainVid(id)
});
});
The code finally ends here and available on @Codepen for download and further research. I personally thank the @freecodecamp for their engaging and simple tutorials and inspiring me to write this article. Hope I am also succeeded in explaining the same through this article.
Thank you for giving your time in reading my post. If you find my ideas interesting do follow me on twitter @oraajan or check out my linkedin page.
Views expressed in this article are my personal.