Monday, June 13, 2016

Change video property on innerHtml of an IFrame

Leave a Comment

I have this iframe for my embed youtube video:

<iframe class="event-video" src="http://www.youtube.com/embed/myvideoid?showinfo=0&autoplay=1&loop=1&playlist=myvideoid&controls=0&modestbranding=1&iv_load_policy=3"></iframe> 

I use loop=1 to loop the video, but everytime it restarts it loads again (the video freezes for a few seconds with the "loading" gif of youtube).

Since I want my video to loop continuously (seamless), this solution does not please me.

I discovered that if I right click on the video it shows me a HTML5 video box with some options, one of them to "loop" the video. If I click on this option, it changes the video element on the innerHtml of the iframe adding loop property to it.

enter image description here

And it solves my problem. The video doesn't reload on every loop anymore. My question is: how can I do this with jQuery? Is there some safe way to add this loop property on video element of iframe's innerHtml?

1 Answers

Answers 1

There is no way for you to change that because the video is not played on the same domain that your code is, which mean you cannot access the elements inside that iframe, however you can use youtube's JS API in order to loop your video when it ends.

This code will not add the "loop" attribute to the <video> element inside the iframe, but it will give you the loop feature that you are looking for (without reloading the video, just play it from the beginning):

    <!doctype html>      <html lang="en">          <head>              <meta charset="utf-8">              <title>Test</title>              <script src="http://www.youtube.com/player_api"></script>          </head>          <body>          <div id="player"></div>          <script type="text/javascript">              var player;              function onYouTubeIframeAPIReady() {                  player = new YT.Player('player', {                      height: '390',                      width: '640',                      videoId: 'M4Xrh8OP1Jk',                      events: {                      'onReady': onPlayerReady,                      'onStateChange': onPlayerStateChange                      }                  });              }                function onPlayerReady(event) {                  event.target.playVideo();              }                function onPlayerStateChange(event) {                  console.log(event.data)                  if (event.data == YT.PlayerState.ENDED) {                      event.target.playVideo();                  }              }          </script>    </body>  </html>

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment