YouTube video autoplay on mobile

I made a landing with article blocks and some of them are containing video content from YouTube.
When user scrolls the page, and when the block which contains the video is in the device viewport, video element must start playing. I made this using YouTube API, but it does’t work on mobile devices.
Is there a way to make it work on mobile? Or maybe there is another way to embed and control YouTube video without using iFrame?

35 thoughts on “YouTube video autoplay on mobile”

  1. <!DOCTYPE html>
    
    <html>
    
    <head>
    
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    
    <script>
    
    $(document).ready(function(){
    
    $("p").click(function(){
    
    $(this).hide();
    
    });
    
    });
    
    </script>
    
    </head>
    
    <body>
    
    <!-- 1. The <iframe> (video player) will replace this <div> tag. -->
    
    <div id="player"></div>
    
    <script>
    
    // 2. This code loads 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);
    
    // 3. This function creates an <iframe> (and YouTube player)
    
    // after the API code downloads.
    
    var player;
    
    function onYouTubeIframeAPIReady() {
    
    player = new YT.Player('player', {
    
    width: '100%',
    
    videoId: '(Youtube Video ID add Here)',
    
    playerVars: { 'autoplay': 1, 'playsinline': 1 },
    
    events: {
    
    'onReady': onPlayerReady
    
    }
    
    });
    
    }
    
    // 4. The API will call this function when the video player is ready.
    
    function onPlayerReady(event) {
    
    event.target.mute();
    
    event.target.playVideo();
    
    }
    
    </script>
    
    </body>
    
    </html>
    Reply

Leave a Comment