toggle between two youtube videos

I try to toggle between two youtube videos. This is my try:

const videoIDs = ["puAoFjGcQZI", "KEmBRLr3jsc"];

let currentVideoIndex = 0;

const videoElement = html`<iframe width="560" height="315" src="https://www.youtube.com/embed/${videoIDs[currentVideoIndex]}" frameborder="0" allowfullscreen></iframe>`;

const switchButton = html`<button>Switch Video</button>`;
switchButton.addEventListener("click", () => {
  currentVideoIndex = (currentVideoIndex + 1) % videoIDs.length;
  videoElement.src = `https://www.youtube.com/embed/${videoIDs[currentVideoIndex]}`;
});

html`${videoElement}${switchButton}`

This doesnt work. Could anybody help me? Thank you!

1 Like

It doesn’t look to me like you’re leveraging the full power of Observable. I’d create an iFrame embed like so:

html`<iframe width="560" height="315" 
  src="https://www.youtube.com/embed/${vid.code}"
  frameborder="0" allowfullscreen>
</iframe>`

In a separate cell, I’d setup vid as a view:

viewof vid = {
  let choices = [
    { code: "tRYKAMjKgto", singer: "Bob" },
    { code: "crVB0uGeHPM", singer: "Jimi" }
  ];
  return Inputs.radio(choices, {
    label: "Performer",
    format: (o) => o.singer,
    value: choices[0]
  });
}

You can see the result in this notebook:


To get a better understanding of these things, you might read: