Tuesday, 29 December 2015

Youtube player HTML5 wrapper

To make the Youtube Player API easier to use, Ginpei, has created an excellent Youtube Javascript wrapper called html5-youtube.js. With this plugin, Youtube players can be embedded into your HTML page with ease. I have written a few examples below for future reference and for anyone else to learn.

The first example is self explanatory you replace the videoID with the Youtube video you want to use. For simplicity sake I have written all code on one page.

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Youtube player HTML5 wrapper example 1</title>
</head>
<body onload="init()">

    <div id="youtube-player"></div>

    <script src="html5-youtube.min.js"></script>
    <script>
        function init(){
            var playerElement = document.querySelector('#youtube-player');
            var videoId = 'YL9RetC0ook';
            var player = youtube({ el:playerElement, id:videoId });
        }
    </script>
</body>
</html

The second example swaps the Youtube video depending on the button clicked.
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Youtube player HTML5 wrapper example 2</title>
</head>
<body onload="init()">

    <div id="youtube-player"></div>

    <div>
        <button class="video1">Video 1</button>
        <button class="video2">Video 2</button>
        <button class="video3">Video 3</button>
    </div>
    
    <script src="html5-youtube.min.js"></script>
    <script>
        function init()
        {
            var playerElement = document.querySelector('#youtube-player');
            var videoId = 'YL9RetC0ook';
            var player = youtube({ el:playerElement, id:videoId });
            
            var button1 = document.querySelector('.video1');
            var button2 = document.querySelector('.video2');
            var button3 = document.querySelector('.video3');
            
            button1.addEventListener('click', swapVideo);
            button2.addEventListener('click', swapVideo);
            button3.addEventListener('click', swapVideo);
            
            function swapVideo(e)
            {
                switch(e.currentTarget.className)
                {
                    case 'video1':
                        player.src = "YL9RetC0ook";
                        break;
                    case 'video2':
                         player.src = "G-og553jauM";
                        break;
                    case 'video3':
                        player.src = "KK9bwTlAvgo";
                        break;    
                }
            }
        }
        
    </script>
</body>
</html>

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP