Using JavaScript to embed a YouTube video

This example uses JavaScript to create an iframe and play the YouTube video on click of the anchor.

Cover image of video (standard definition)
Die Burger 42km MTB Challenge 2012 [Part 9 of 11] [GoPro HD Hero2]


<figure class="figure">
    <a class="js-embed-iframe" href="" target="_blank">
        <img src="" width="640" height="480" alt="Cover image of video (standard definition)">

    <figcaption>Die Burger 42km MTB Challenge 2012 [Part 9 of 11] [GoPro HD Hero2]</figcaption>


    // Get all iframes to be embedded
    var embeds = document.querySelectorAll('.js-embed-iframe');

    embeds.forEach(function (embed) {
        // Get the href from the anchor for each iframe to be embedded
        var url = embed.getAttribute('href');

        // Check that there is a URL
        if (typeof url !== 'undefined' && url !== '') {

            // Add an on click event listener to the anchor
            embed.addEventListener('click', function (e) {
                var anchor = this;

                // Prevent clicking through to the href

                // Create the iframe and set the source attribute to the value of the anchor’s href
                var iframe = document.createElement('iframe');
                iframe.setAttribute('src', url);

                // Get the parent of the anchor and replace the anchor with the iframe + remove the figure’s caption
                var parent = anchor.parentNode;
                parent.replaceChild(iframe, anchor);

Read about the default method for embedding a YouTube video.

Or go back to the performance comparision of these two methods.