Nick Gilbert Nick Gilbert - 1 year ago 67
jQuery Question

Autoplaying a full screen YouTube video on button press with JQuery

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

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

a href="javascript:void(0);" onclick="addIntroVideo()"

and this is my jQuery function

function addIntroVideo() {
$('<iframe id="introVideo" src="" 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?

Answer Source

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download