Reputation: 327
I am loading a few videos on my webpage using the iframe tag.
<iframe id="player" type="text/html" width="640" height="280" src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0">
</iframe>
Initially, I am providing a dummy url - "https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" as src attribute to the iframe tag, which I am using to embed the YouTube video. I have separated the video loading and video playing functionalities by creating two separate functions. This is because I am queueing a video on clicking a link, and only playing it when some settings are enabled.
function playOnClick() {
player.playVideo();
}
function loadOnClick(videoId, videoURL) {
// videoURL contains the url of video in the following format - https://www.youtube.com/watch?v=videoID
/*
videoURL = videoURL.replace(/watch\?v\=/, 'embed/');
videoURL += '?enablejsapi=1';
jQuery('#player').attr('src', videoURL);
*/
player.cueVideoById(videoId);
}
The above code works fine. However, if I uncomment the commented portion of dynamically updating the src attribute of iframe, the src is updated and the video is also queued, but it doesn't play.
Also, when I try the above code(after uncommenting the commented portion) with no dummy src attribute, it throws an error message like this -
Uncaught TypeError: Object # has no method 'loadVideoById'
This I guess is probably because it fails to recognize that enablejsapi is set to true.
What is the best possible to update the src attribute of iframe, and make the code work without providing a dummy src to the iframe tag?
Thanks in advance!
Upvotes: 0
Views: 1273
Reputation: 13667
This is the expected behavior; if you change the iframe src outside of the API, you break the bindings that the API creates. The best way around this is to not create your iframes at all, but let the API do it for you (you just create empty tags, then create a YT.Player object for each div ... and the DOM nodes will be injected for you, already bound to the iframe API. See https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player for an example of how you pass the ID of an empty to the constructor), and then always use loadVideoById to change videos.
Having said that, if you'd rather create the iframes manually, still, if the code you've got (with the jquery commented out) works, you can go with that ... is there a compelling reason to have jquery manually change the src attribute (when cueVideoById is already going to do it programmatically)?
Upvotes: 1