How can I retrieve the duration of a video using the YouTube Data API?

Essentially, I am attempting to extract the video duration for each video that appears in the search results. Feel free to play around with the demo I have prepared!

Additionally, when I refer to duration, I am talking about the length of the video in M/S format (0:00)..

DEMO http://codepen.io/mistkaes/pen/6b6a347c7d24edee15b3491420db4ecd

jQuery:

var apikey = '<API KEY>';

$(function() {
    var searchField = $('#search-input');

    $('#search-form').submit(function(e) {
        e.preventDefault();
    });
});

function search() {
    $('#results').html('');

    q = $('#search-input').val();

    $.get(
        "https://www.googleapis.com/youtube/v3/search", {
            part: 'snippet, id',
            q: q,
            maxResults: 50,
            type: 'video',
            key: apikey
        },
        function(data) {
            $.each(data.items, function(i, item) {
                var output = getResults(item);

                $('#results').append(output);
            });
        });
}

function getResults(item) {
    var videoID = item.id.videoId;
    var title = item.snippet.title;
    var thumb = item.snippet.thumbnails.high.url;
    var channelTitle = item.snippet.channelTitle;

    var output = '<li>' +
        '<div class="list-left">' +
        '<img src="' + thumb + '">' +
        '</div>' +
        '<div class="list-right">' +
        '<h3><a href="http://youtube.com/embed/' + videoID + '?rel=0">' + title + '</a></h3>' +
        '<p class="cTitle">' + channelTitle + '</p>' +
        '</div>' +
        '</li>' +
        '<div class="clearfix"></div>' +
        '';

    return output;
}

Answer №1

Upon researching your query, it appears there is a known issue with the search API.

As an alternative solution, you can utilize the Youtube Data API's Video resource after initiating the search call. This allows you to input up to 50 video IDs in the search, eliminating the need to call it for each individual element.

I have made updates to your codepen, implementing the following changes:

1) Obtain the URL of each video retrieved from the search results.

2) Initiate another Ajax call to retrieve the duration:-

for (var i = 0; i < data.items.length; i++) {
    var url1 = "https://www.googleapis.com/youtube/v3/videos?id=" + data.items[i].id.videoId + "&key=AIzaSyDYwPzLevXauI-kTSVXTLroLyHEONuF9Rw&part=snippet,contentDetails";
    $.ajax({
        async: false,
        type: 'GET',
        url: url1,
        success: function(data) {
            if (data.items.length > 0) {
                var output = getResults(data.items[0]);
                $('#results').append(output);
            }
        }
    });
}

3) The API provides time in ISO format, so I converted it into mm:ss format as per your request.

function convert_time(duration) {
    var a = duration.match(/\d+/g);

    // Additional code for handling different cases

    return ((h > 0 ? h + ":" + (m < 10 ? "0" : "") : "") + m + ":" + (s < 10 ? "0" : "") + s);
}

4) Append the resulting duration with the title of your video.

'<p class="cTitle">' + channelTitle + '  --->' + duration + '</p>'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Loading Power of jQuery and the Impact of Facebook Comments

In a nutshell: Facebook comments are not appearing when loaded from another page using jQuery.load() in a lightbox-type format. However, the comments do show up when directly visiting the page being loaded in the lightbox. I have created a custom lightbox ...

Styling Overlapping Divs with CSS3

I am attempting to replicate this particular effect using HTML within the UIWebView control on iOS. The desired outcome is to simulate a progress bar on the listing. My current approach involved utilizing this method, however, as you can observe, adding pa ...

Automated Recommendation Selector

I'm searching for a JavaScript library that can provide the following functionalities: An auto-suggest dropdown list that uses Ajax to retrieve results from a database. Restricting the user to only select values provided by the Ajax call. Abilit ...

Having trouble with my ReactJS application where click interactions are functioning properly on the header but not on my content

Objective: Implement an iframe displaying a YouTube video with play/pause functionality for users. Issue: Unable to interact with main content, but works correctly when placed in Navigation or Footer components. Attempted Solutions: Explored various de ...

What is the best method for binding variables in Vue.JS using moustache syntax and passing parameters to them?

If I have an HTML structure like this: <div> {{ CUSTOM_MESSAGE }} </div> And in my data: data() { return { CUSTOM_MESSAGE: 'Hey there! This message is for {{name}} from {{location}}' } } Is there a way to dynamically p ...

No action taken with response after $.ajax call was completed

Having trouble populating my select menus with the data received from an ajax call. The response is coming back, but the .html call is not recognizing it. I attempted using success: and .done, but they were not triggering at all. $ -> $('#vehicl ...

What is the best way to determine if a user is logged in on one tab but not on another tab within the same browser session?

GitHub has recently introduced a new functionality where if you are browsing a page as a guest in one tab and then log in from another tab, the tab where you are still a guest will show a specific message. This feature also functions in incognito or privat ...

The XML request fails to retrieve any output from the PHP script

I am seeking tools to enable the calling of .php from .html files. Here is an issue: while this example successfully works in a .php file: <html> <head> <meta http-equiv="content-type" content="text/html" charset="utf-8"> &l ...

Ways to elegantly re-establish a websocket connection?

I've been working on a single-page application that utilizes HTTP and Websockets. When the user submits a form, I start streaming a response back to the client. Here's a snippet of the client-side code: var html = `<!DOCTYPE html> <met ...

The click event for jQuery is failing to trigger on every link

Currently, I'm in the process of creating a "collapse all" button for the Bootstrap 3 collapsible plugin. It appears to be functioning correctly, but only when there is just one collapsible on the page. Once I add another one, the method only works on ...

Is it possible to replicate the functionality of RadTreeList in Gridview/Jquery?

There is a control called RadTreeList by Telerik that we do not use in our current project, but wish we did. If you want to see an example of it, you can visit this link: Currently, I need to find a way to represent the number of applications associated ...

Loading items into the select menu

In my database, I have a table with 3 columns: ID, TITLE, TEXT. These will be used to populate select options in a form. When a user makes a selection, a script will take the title and text, make some adjustments, and store it in a different table. My que ...

Retrieving JSONP data from Wunderground using jQuery

Having trouble parsing data from the "wunderground" API using JavaScript and Ajax. Some values are returned successfully, while others are not. Here is the link to the API I am utilizing: { "forecast":{ "simpleforecast":{ "forecastday":[ ...

The style of a button element is lost when hovering over it after the background color has

This question is related to CSS. If you look at this example, you will see a button with two span elements inside. One using float:left; and the other using float:right;. The button has a typical button-style, but when clicked on an iPhone or hovered over ...

When I use Ajax to update my HTML, it causes Javascript to malfunction

Encountering an issue with a web application I've been developing recently, specifically related to ajax reloading causing javascript to fail. The following Ajax Call is in place $.ajax({ type: "POST", url: "/sortByI ...

Is there a way to modify the CSS or add custom styling within an iframe form?

Currently I am working on the following page: , where an embedded javascript form called infusionsoft (iframe form) needs to be made responsive at the request of my client. I'm wondering if there is a way to override the css or inject custom styles i ...

Trouble detecting click event in jQuery after triggering radio button in HTML

Encountering a peculiar jQuery issue where triggering a click on a radio button does not fire completely and is ignored by an on click function, while a similar call to the jQuery trigger method is successfully captured. In the below jQuery snippet, a < ...

Exchange the draggable elements between distinct div containers while keeping them in their original positions

Attempting to create an example showcasing Draggable jQuery with Bootstrap, everything is functioning smoothly so far. However, there are two things I am aiming to achieve: Swap the divs <div class='col-sm-12'></div> that were gen ...

I am currently working on developing an HTML and JavaScript audio player that can play audio at specific scheduled times

Looking to create a custom HTML/JavaScript audio player that adjusts playback based on the time of day. For instance, if it's 1:00 pm, the file will start playing from 0:00 minutes; and if it's 1:01 pm, the file will begin playing from 1:00 minut ...

What causes discrepancies between jQuery set attributes and .html() output?

In an attempt to set attributes on HTML snippets, I am aiming to repopulate a form with previously entered values. Despite using .attr() to set the attributes, they do not appear after using .html(). For reference, I have provided a simple example here: h ...