jQuery & JSON function to make YouTube video title the iframe ID

By [email protected]

by Ryan Brackett

HTML

<h1>Make YouTube video title the iframe ID</h1>
This will work for any YouTube iframe embed. Useful when using youtube ga tracking codes on the website. Use your browser html inspect tool to view the id's on each of the two video iframes.
<br/>
<br/>
<br/>
<iframe src="https://www.youtube.com/embed/dPg_LPAgQSw"></iframe>
<br/>
<br/>
<iframe src="https://www.youtube.com/embed/6n0rdQ7GYKU"></iframe>
<br/>
<br/>By [email protected]

CSS

body {
    padding: 20px;
    font-family: arial;
}
h1 {
    font-size: 25px;
    margin-top: 0px;
}
.gaplayer {
    width: 100%!important;
    font-size: 12px!important;
    height: 0px!important;
    padding-bottom: 56.2%!important;
    position: relative!important;
}
.youtube-iframe {
    width: 100%!important;
    height: 100%!important;
    position: absolute!important;
}

JavaScript

$("iframe[src*='youtube.com']").each(function () {

    var current_vid = $(this);
    var video_id = $(this).attr("src").replace("https:", "").replace("//www.youtube.com/embed/", "");

    $(current_vid).addClass("youtube-iframe").wrap("<div class='gaplayer'></div>");

    // perform json function to get video title
    $.getJSON("http://gdata.youtube.com/feeds/api/videos?q=" + video_id + "&v=2&alt=jsonc", function (data) {
        var video = data.data.items[0],
            id = video.id,
            title = (video.title).toLowerCase().replace(/[^a-zA-Z0-9]+/g, "-");
        // makes video title the iframe ID
        $(current_vid).attr('id', title);

    });

    // set iframe embed parameters for styling and js enabling
    var embed_parameters = "?rel=0&showinfo=0&iv_load_policy=3&autohide=1&wmode=transparent&enablejsapi=1";
    $(".gaplayer .youtube-iframe").attr("frameborder", 0).attr('src', function (i, currentAttribute) {
        return currentAttribute + embed_parameters;
    });

});