Autoplay Youtube Video When Scrolled to

后端 未结 3 1419
半阙折子戏
半阙折子戏 2020-12-30 15:45

Is there any way to autoplay a youtube video when you scroll to it on the page? I\'ve tried to google this and it looks like theres some methods for the old youtube embed c

3条回答
  •  醉酒成梦
    2020-12-30 16:21

    I'm aware this is an old question but I found a solution that fits my need perfectly so I thought I would share it. I found out you can actually append &autoplay=1 to the iframe src, it automatically plays the video.

    $(window).scroll(function() {
     
    //will trigger when your element comes into viewport
        var hT = $('#YourElement').offset().top,
        hH = $('#YourElement').outerHeight(),
        wH = $(window).height(),
        wS = $(this).scrollTop();
    
    
    
    if (wS > (hT+hH-wH)){
        //appends &autoplay=1 to iFrame src, making it autoplay
        var videoUrl = $('#YourIFrame').attr('src');
        $('#YourIFrame').attr('src', videoUrl + "&autoplay=1");
    }
    

提交回复
热议问题