Reputation: 109
I am looking to have a YouTube video start playing as the iframe enters the viewport.
jQuery(document).ready(function() {
var inner = jQuery("#auto-video iframe");
var elementPosTop = inner.position().top;
var viewportHeight = jQuery(window).height();
jQuery(window).on('scroll', function() {
var scrollPos = jQuery(window).scrollTop();
var elementFromTop = elementPosTop - scrollPos;
if (elementFromTop > 0 && elementFromTop < elementPosTop + viewportHeight) {
inner.get(0).play();
} else {
inner.get(0).pause();
}
});
This returns a "play is not a function" message in the console.
EDIT
<div id="auto-video">
<iframe width="450" height="253" src="https://www.youtube.com/embed/wCdl3nGPDgE?rel=0&controls=0&showinfo=0&autoplay=0" frameborder="0" allowfullscreen></iframe>
</div>
Upvotes: 1
Views: 2260
Reputation: 51
Even though this is an old thread, I found a solution and thought I'd post it in-case it's useful for anyone.
Using the code below, it will play the embedded YouTube video when the user scrolls to your element. Just fill in "#YourElement" with the element that will play the video when they scroll to it. Finally, give your iFrame and ID attribute and change "#YourIFrame" to whatever you called the ID of your iFrame.
$(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");
}
Upvotes: 2