LovelyAndy
LovelyAndy

Reputation: 891

Vanilla JS: Autoplay Video Inside A Modal

Is there anyway in vanilla JS to have a video autoplay inside of a popup modal? Is it even possible?

I have the autoplay element in the iframe (think it comes standard in the embedded link from YT), but I still have to click play when the modal pops up.

Also, when you press play and then close the modal, the video still plays. I have yet to find a way to stop that with anything other than a refresh (my guess is it is because the modal is always technically on the page and I just have it hidden).

Not sure if I need anymore information than just the line that I use to call the modal in JS, but I have this:

xmasDayModalTextEl.innerHTML = `<iframe
  width="543"
  height="362"
  src="https://www.youtube.com/embed/VzkVxkiOqGA"
  frameborder="0"
  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen
></iframe>`

If you need anymore code to get a better idea of how it all works please let me know! I thought it may just be the way I write the innerHTML!

Cheers!

Upvotes: 0

Views: 913

Answers (1)

83C10
83C10

Reputation: 1212

YouTube's iframe allows to trigger autoplay via the autoplay=1 URL parameter: <iframe src="https://www.youtube.com/embed/VzkVxkiOqGA?autoplay=1" ...>. Also, you could do it with YouTube JavaScript API.

In order to stop the video after closing the modal you could remove the iframe from the DOM altogether. As a consequence, you would also have to insert it when the user opens the modal.

const modal = document.querySelector('#modal-id');
const iframe = `<iframe ... ></iframe>`;

function showModal() {
  modal.innerHTML = iframe;
}

function hideModal() {
  modal.innerHTML = '';
}

Upvotes: 1

Related Questions