Search code examples
jqueryyoutube-apiembeddingyoutube-javascript-api

YouTube API: custom button to start playing an embedded video


I have embedded a YouTube video in a website, but I want to start playing it by clicking on a custom button outside the player.

After some research on the web I've tried with this piece of js:

$(document).ready(function() {
    $.getScript('http://www.youtube.com/player_api');


    $('#playvideo').click( function() {
         thevid=document.getElementById('thevideo'); thevid.style.display='block'; this.style.display='none'; $('#video').playVideo();
    });
});

where #playvideo is the button and #video is the YouTube iframe.

And this is the embedding html code:

<iframe id="video" width="266" height="150" src="http://www.youtube-nocookie.com/embed/uJnHiN-GsZM?rel=0&showinfo=0&controls=2&enablejsapi=1" frameborder="0" allowfullscreen></iframe>

but it's not working on any browser and I'm receiving this JS error:

Uncaught TypeError: Object [object Object] has no method 'playVideo'

anyone can give me some suggestion?


Solution

  • You are referencing the video with an ID of thevideo here:

    document.getElementById('thevideo')

    But you later try referencing the video with an ID of video here:

    $('#video').playVideo();

    Make sure all of your IDs and references are correct. Then let us know if the problem persists.