Beneath some other content on a page, I have an embedded Vimeo video in an iframe within a containing div. Here's an idea of the what the HTML looks like:
<div>Some content goes here</div>
<div id="video-container">
<iframe id="video" src="https://player.vimeo.com/video/123456789?autoplay=1&loop=1&muted=1&title=0&byline=0&portrait=0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" width="530" height="298" frameborder="0"></iframe>
</div>
What I would like to do is have the video autoplay as soon as any part of the div containing the iframe is in the viewport, and stop it when the div is out of the viewport. I've been working on JS based on this: https://gomakethings.com/how-to-test-if-an-element-is-in-the-viewport-with-vanilla-javascript/ and this: https://gist.github.com/davidtheclark/5515733 and also this: Autoplay Youtube Video When Scrolled to. Here's what I've come up with:
<script>
var dv = document.getElementById('video-container');
var v = document.getElementById('video');
function isAnyPartOfElementInViewport(dv) {
const rect = dv.getBoundingClientRect();
const windowHeight = (window.innerHeight || document.documentElement.clientHeight);
const windowWidth = (window.innerWidth || document.documentElement.clientWidth);
const vertInView = (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);
const horInView = (rect.left <= windowWidth) && ((rect.left + rect.width) >= 0);
return (vertInView && horInView);
}
window.addEventListener('scroll', function (event) {
if (isAnyPartOfElementInViewport(dv)) {
if (v.src=='' || v.src==location.href) {
v.src='https:/player.vimeo.com/video/123456789?autoplay=1&loop=1&muted=1&title=0&byline=0&portrait=0';
}
}
else {
v.src='';
}
}, false);
</script>
This works the way I want it to on Firefox, Safari, and Chrome, but doesn't work correctly on IE11 and IE10. The video only plays in IE if it's within the viewport on page load and I don't have to scroll to it. If the video is out of the viewport to begin with, it does not show when I scroll to it.
Thanks for any help on this issue! Quick additional note: I am looking for a plain JavaScript solution (no jQuery).
Edited to add: I think the problem is with this part:
if (v.src=='' || v.src==location.href) {
If I remove this conditional statement and set a new src for the video regardless of whether the video is already playing, then it works in IE11. However, a conditional is needed because I don't want the video to reload if it's already playing.