D45
D45

Reputation: 101

How do I create a button that plays a youtube video in HTML?

I have the following code. My button works fine, however I cant figure out how you make the function work.

My goal is to create a button that when clicked opens up the iframe for a youtube video/makes it visible.

<body>

<div class="bgimg w3-display-container w3-animate-opacity w3-text-white">
<div class="w3-display-middle">
<h1 class="w3-jumbo w3-animate-top">TAKE YOUR MARK</h1>
<hr class="w3-border-grey" style="margin:auto;width:40%">
  <p><button class="w3-center center transparent_btn" 
onclick="play1()">go</button></p>
  </div>
</div>
</body>

<script>
function play1() { 
    <iframe width="560" height="315" src="https://www.youtube.com/embed/AkFs3YzxN_E" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
  }

Upvotes: 0

Views: 6372

Answers (2)

pjones235
pjones235

Reputation: 540

You need to have an element that the iframe can be inserted into.

<body>

<div class="bgimg w3-display-container w3-animate-opacity w3-text-white">
<div class="w3-display-middle">
<h1 class="w3-jumbo w3-animate-top">TAKE YOUR MARK</h1>
<hr class="w3-border-grey" style="margin:auto;width:40%">
  <p><button class="w3-center center transparent_btn" 
onclick="play1()">go</button></p>
  <div id="youtube-frame"></div>
  </div>
</div>
</body>

<script>
function play1() { 
    var frame = document.getElementById("youtube-frame");
    frame.innerHTML += "<iframe width='560' height='315' src='https://www.youtube.com/embed/AkFs3YzxN_E' frameborder='0' allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>";
  }
</script>

Upvotes: 1

Sibtain
Sibtain

Reputation: 1

Although youtube offers an API to control the player, but I'll keep things simple. First, add a div inside your body and give it an ID of your choice. Your play1() function should be like this:

    function play1(){
      var player = '<iframe width="560" height="315" 
      src="https://www.youtube.com/embed/AkFs3YzxN_E" frameborder="0" 
      allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in- 
      picture" allowfullscreen></iframe>';
      document.getElementById('ID').innerHtml = player;
    }

Upvotes: 0

Related Questions