Autoplaying a full screen YouTube video on button press with JQuery

时间:2016-10-20 18:54:32

标签: javascript jquery ruby-on-rails youtube slim-lang

My website has a video banner at the top of the home page similar to AirBnb's. It has a play glyphicon on it. When I press the glyphicon, I want a video from YouTube to open in fullscreen mode and play automatically. Then, when the user quits the fullscreen video, I want the Iframe to vanish and all audio to stop.

Right now I have this for Slim markup

.fullScreenContainer
    .video-container#autovid height="100%"
      = video_tag("broll2.mp4", autoplay: true, muted: true, preload:true, loop:true)
    .container#playButton
      .text-center
        h1#videoHeading Press Play to Watch the Video

        a href="javascript:void(0);" onclick="addIntroVideo()"
          span.glyphicon.glyphicon-play

and this is my jQuery function

function addIntroVideo() {
    $('<iframe id="introVideo" src="https://www.youtube.com/embed/6a8fvbkNLWQ?rel=0&autoplay=1" frameborder="0" allowfullscreen="true"></iframe>').appendTo('.fullScreenContainer');
}

My understanding is that appending ?rel=0&autoplay=1 to the YouTube URL makes the video play in full screen mode and start automatically. However, when I press play it just loads a tiny iframe and autoplays that. How do I change this code to get it to do what I want?

1 个答案:

答案 0 :(得分:0)

Don't make the iframe yourself. Instead, use the YouTube iframe API example You can add embedded JavaScript under this Slim tag:

javascript:

That JavaScript creates the iframe and an object called player that has methods stopVideo() and startVideo(), and you can use more JavaScript to hook those functions to a button click handler.