Adam
Adam

Reputation: 11

Uncaught TypeError: Cannot read property 'playVideo' of undefined

when loading the page the Chrome console gives me the following error:Uncaught TypeError: Cannot read property 'playVideo' of undefined

<script>
  // Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // Replace the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',
      playerVars: {
        autoplay: 0
      },
      videoId: 'bvtwWhKdxhM'
    });
  }
  $(window).scroll(function() {
    $("iframe").each(function() {
      if ($(window).scrollTop() > $(this).offset().top - 800) {
        $(this).css('opacity', 1);
        player.playVideo();
      } else {
        $(this).css('opacity', 1);
        player.stopVideo();
      }
    });
  });
</script>

Upvotes: 1

Views: 2707

Answers (2)

JITENDRA PATIL
JITENDRA PATIL

Reputation: 21

Please check function onYouTubeIframeAPIReady is getting call or not. For testing just put console.log('onYouTubeIframeAPIReady') in function onYouTubeIframeAPIReady and check in console.

Upvotes: 0

Alfonso Cavalieri
Alfonso Cavalieri

Reputation: 21

I tried to run the code and It works.

This is my whole page:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>youtube demo</title>

  <div id="ytplayer"></div>

 <script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<script>
  // Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // Replace the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',
      playerVars: {
        autoplay: 0
      },
      videoId: 'bvtwWhKdxhM'
    });
  }
  $(window).scroll(function() {
    $("iframe").each(function() {
      if ($(window).scrollTop() > $(this).offset().top - 800) {
        $(this).css('opacity', 1);
        player.playVideo();
      } else {
        $(this).css('opacity', 1);
        player.stopVideo();
      }
    });
  });
</script>

</body>
</html>

Upvotes: 2

Related Questions