Search code examples
htmlmobileyoutubefancyboxoverlay

autoplay not working on mobile devices YouTube video


The video is not working in autoplay on mobile, I know that the question has already been asked several times but the code was developed specifically for my site (by a developer who answers me more). So I can't change it entirely, could I tell me what to add to make it work?

<script>
var player;

function onYouTubePlayerAPIReady() {
  player = new YT.Player('player', {
    playerVars: {
      'autoplay': 1,
      'controls': 0,
      'autohide': 1,
      'wmode': 'opaque',
      'showinfo': 0,
      'loop': 1,
      'mute': 1,
      //'start': 15,
      //'end': 110,
      'playlist': '{{ product.metafields.left_image.left_image[forloop.index0] }}'
    },
    videoId: '{{ product.metafields.left_image.left_image[forloop.index0] }}',
    events: {
      'onReady': onPlayerReady
    }
  });

}

function onPlayerReady(event) {
  event.target.mute();
  $('#text').fadeIn(400);
  //why this? Well, if you want to overlay text on top of your video, you
  //will have to fade it in once your video has loaded in order for this
  //to work in Safari, or your will get an origin error.
}

//this pauses the video when it's out of view, just wrap your video in .m-//video
$(window).scroll(function() {
  var hT = $('.m-video').height(),
      wS = $(this).scrollTop();
  if (wS > hT) {
    player.pauseVideo();
  }
  else {
    player.playVideo();
  }
});

</script>

Solution

  • you can add the following code in the end of the onPlayerReady function:

    if(window.innerWidth < 768) {
      player.playVideo();
    }
    

    This code will start playing the video on mobile devices by checking the screen size.