Dinesh Jayapal
Dinesh Jayapal

Reputation: 51

How to use the YouTube Api in html iframe?

Trying to add the "Pause" and "Play" button manually for Youtube API in my HTML document. My javascript functions is not working. Don't know how insert my javascript function . I have posted my document coding with script. Please help me.

 <!DOCTYPE html>
<html>
<head>
<title>Chumma</title>
<style>

.button {
  width: 48px;
  height: 48px;
  cursor: pointer;
  &:hover {
    fill: white; 
  }
}

.defs {
  position: absolute;
  top: -9999px;
  left: -9999px;
}

iframe {
  float: left;
  width: 300px;
  height: 200px;
}

.buttons {
  padding: 1rem;
  background: #f06d06;
  float: left;
}

body {
  padding: 1rem;
}

</style>



</head>


<body>

<h1>Pause / Play Buttons for YouTube Videos</h1>

<iframe id="video" src="https://www.youtube.com/embed/MV_ITkqLzik?enablejsapi=1&html5=1" frameborder="0" allowfullscreen></iframe>

-->
<svg class="defs">
  <defs>
    <path id="pause-button-shape"  d="M24,0C10.745,0,0,10.745,0,24s10.745,24,24,24s24-10.745,24-24S37.255,0,24,0z M21,33.064c0,2.201-1.688,4-3.75,4
    s-3.75-1.799-3.75-4V14.934c0-2.199,1.688-4,3.75-4s3.75,1.801,3.75,4V33.064z M34.5,33.064c0,2.201-1.688,4-3.75,4
    s-3.75-1.799-3.75-4V14.934c0-2.199,1.688-4,3.75-4s3.75,1.801,3.75,4V33.064z"/>
    <path id="play-button-shape"  d="M24,0C10.745,0,0,10.745,0,24s10.745,24,24,24s24-10.745,24-24S37.255,0,24,0z M31.672,26.828l-9.344,9.344
    C20.771,37.729,19.5,37.2,19.5,35V13c0-2.2,1.271-2.729,2.828-1.172l9.344,9.344C33.229,22.729,33.229,25.271,31.672,26.828z"/>
  </defs>
</svg>

<div class="buttons">
  <svg class="button" id="play-button">
    <use xlink:href="#play-button-shape">
  </svg>
  <svg class="button" id="pause-button">
    <use xlink:href="#pause-button-shape">
  </svg>
</div>


<script type="text" language="javascript">


var player;


function onYouTubePlayerAPIReady() {

  player = new YT.Player('video', {
    events: {
         'onReady': onPlayerReady
    }
  });
}

function onPlayerReady(event) {

  var playButton = document.getElementById("play-button");
  playButton.addEventListener("click", function() {
    player.playVideo();
  });

  var pauseButton = document.getElementById("pause-button");
  pauseButton.addEventListener("click", function() {
    player.pauseVideo();
  });

}


var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

</script>



</body>
</html>

Upvotes: 0

Views: 139

Answers (1)

Shailendra Sharma
Shailendra Sharma

Reputation: 6992

You code Working fine u need to just initiate onYouTubePlayerAPIReady() function at the end of script (better init in $(document).ready)

here the working fiddle with your code http://jsfiddle.net/wfttwmre/

Upvotes: 1

Related Questions