Pause And Play Video When In Viewport
Solution 1:
I agree with what you said in your question: users might not like it, especially if they're on mobile and you're sucking all their data plan. Anyway, here's how to check if an element is in the viewport: http://jsfiddle.net/pwhjk232/
$(document).ready(function() {
var inner = $(".inner");
var elementPosTop = inner.position().top;
var viewportHeight = $(window).height();
$(window).on('scroll', function() {
var scrollPos = $(window).scrollTop();
var elementFromTop = elementPosTop - scrollPos;
if (elementFromTop > 0 && elementFromTop < elementPosTop + viewportHeight) {
inner.addClass("active");
} else {
inner.removeClass("active");
}
});
})
Instead of using addClass you could use .get(0).play()
and .get(0).pause()
as suggested by Vohuman
Solution 2:
There are several errors in your code:
$(window).scroll(100)
is not comparison. You are passing an integer to thescroll
method which is used for attachingscroll
listener. You should usescrollTop()
method and use===
or==
for comparison.play
is a method, you should use()
invocation operator for calling the method. But jQuery object doesn't haveplay
method,HTMLVideoElement
object hasplay
method so you should at first get the DOM element object from the jQuery collection.There is no element with ID of
video
in your code, the selector should be#background
.$(window).scroll(function(){ if ($(window).scrollTop() === 100) { $('#background').get(0).play(); } else { $('#background').get(0).pause(); } });
Note that scroll
event is fired many times, you should consider throttling the handler.
Solution 3:
$(window).scroll(function(e)
{
var offsetRange = $(window).height() / 3,
offsetTop = $(window).scrollTop() + offsetRange + $("#header").outerHeight(true),
offsetBottom = offsetTop + offsetRange;
$(".video").each(function () {
var y1 = $(this).offset().top;
var y2 = offsetTop;
if (y1 + $(this).outerHeight(true) < y2 || y1 > offsetBottom) {
this.pause();
} else {
this.play();
}
});
});
Post a Comment for "Pause And Play Video When In Viewport"