0

I have set up some test code that loads in a youtube video and then a jquery click event on a link that I plan to stop the video, at the moment however when I click the link I get the error: Uncaught TypeError: Object [object Object] has no method 'stopVideo'

Can anyone suggest where I might be going wrong with this?

 <div id="container">
    <a href="#">This is the link</a>

    <br /><br />
    <br /><br />

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


 <script>
        var tag = document.createElement('script');
        tag.src = "http://www.youtube.com/player_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        // 3. This function creates an <iframe> (and YouTube player)
        //    after the API code downloads.
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'u1zgFlCw8Aw'
            });
        }

        function onPlayerReady(event) {
            event.target.playVideo();
        }

        $(document).ready(function() {
            $('a').click(function(e) {
                player.stopVideo();
                e.preventDefault();
            });
        });
 </script>
Rob W
  • 341,306
  • 83
  • 791
  • 678
styler
  • 15,779
  • 23
  • 81
  • 135

1 Answers1

3

Your code snippet works as intended in a fiddle. Also, the YouTube Frame API won't function at a file:/// protocol, because of limitations at the postMessage implementation.

I have previously created a custom implementation of the YouTube API, available at YouTube iframe API: how do I control a iframe player that's already in the HTML?. I have successfully executed the stopVideo method at a file:/// protocol.

If you're running your code online, I can only think of one other cause: You're trying to click at the link before the player is ready. To fix it, merge your functions:

    function onPlayerReady(event) {
        event.target.playVideo();
        $('a').click(function(e) { //<--- Binds event to ALL anchors! Are you sure?
            player.stopVideo();
            e.preventDefault();
        });
    });
Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678