Random YouTube video

In this example below you will see how to do a Random YouTube video with some HTML / CSS and Javascript

The code is correct, but the problem is that there are 3.940201e+115 possibilities for a random youtube video ID, which is substantially a larger number than there are YouTube videos that exist. We are pulling random needles out of a humongous haystack.

Thumbnail
This awesome code was written by chrismbarr, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright chrismbarr ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Random YouTube video</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <iframe id="yt" src="" frameborder="0" allowfullscreen></iframe>
<br />
<button type='button' id='try-again'>Get Another</button>
<a id='out' target="_blank"></a>
<pre id='attempts'></pre>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

  

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




</body>

</html>

/*Downloaded from https://www.codeseek.co/chrismbarr/random-youtube-video-aGFfA */
#yt {
  height: 360px;
  width: 640px;
  margin: 0 auto;
}

#attempts{
  height: 300px;
  background: #555;
  color: #FFF;
  padding: 5px;
  overflow: auto;
}

#attempts a{
	color: #0DCFFF;
}

/*Downloaded from https://www.codeseek.co/chrismbarr/random-youtube-video-aGFfA */
//generate an 11 character youtube video ID.
//It might not be valid...
function getRandomVideoId() {
    var codeLength = 11;
    var possibles = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-_";
    var code = "";
    for (var i = 0; i < codeLength; i++) {
        code += possibles.charAt(Math.floor(Math.random() * possibles.length));
    }
    return code;
}

var attempts = 0;
var maxAttempts = 100;

$(function() {
    var $attempts = $('#attempts');
    var $tryAgainBtn = $("#try-again");
    var $iframe = $("#yt");
    var $link = $("#out");

    function getNewVideo() {
        attempts++;

        if (attempts <= maxAttempts) {
            var ytId = getRandomVideoId();
            var testUrl = 'https://gdata.youtube.com/feeds/api/videos/' + ytId + '?v=2&alt=jsonc';
            $attempts.append("<div>#" + attempts + ": <a href='" + testUrl + "' target='_blank'>" + ytId + "</a> - <span id='a" + attempts + "' style='color: #CCC;'>Loading...</span>" + "</div>");
            $tryAgainBtn.attr("disabled", true);
            $link.html('').attr('href', '#');
            $iframe.attr('src', '');

            $.ajax({
                url: testUrl,
                timeout: 1000,
                error: function(jqxhr, textStatus, thrownError) {
                    $("#a" + attempts).text(jqxhr.responseJSON.error.message || "Invalid ID!").css('color', 'red');
                    getNewVideo();
                },
                success: function(data, textStatus, jqXhr) {
                    $tryAgainBtn.attr("disabled", false);
                    $("#a" + attempts).text("Valid ID!").css('color', 'green');
                    $link.html('Open video <b>' + ytId + '</b> on YouTube').attr('href', 'https://youtube.com/watch?v=' + ytId);
                    $iframe.attr('src', '//www.youtube.com/embed/' + ytId + '?rel=0&autoplay=1');
                }
            });
        } else {
            $tryAgainBtn.attr("disabled", false);
            $attempts.append("<div>Attempted " + maxAttempts + " videos... stopping.</div>");
        }

        $attempts[0].scrollTop = $attempts[0].scrollHeight;
    }

    getNewVideo();
    $tryAgainBtn.on("click", function() {
        attempts = 0;
        $attempts.empty();
        getNewVideo();
    });
});

Comments