Skip to content

Instantly share code, notes, and snippets.

@jiulongw
Created August 26, 2018 06:03
Show Gist options
  • Save jiulongw/b96b25c156336e64a549531ca74b7288 to your computer and use it in GitHub Desktop.
Save jiulongw/b96b25c156336e64a549531ca74b7288 to your computer and use it in GitHub Desktop.
play video when scrolled to w/ wechat browser support
(function($, document, window) {
var ua = navigator.userAgent.toLowerCase();
var isWechat = ua.indexOf("micromessenger") >= 0;
var Player = function(videos) {
this.init(videos);
};
Player.prototype.init = function(videos) {
this.videos = [];
videos.each($.proxy(function(i, el) {
var $el = $(el);
$el.attr("playsinline", "true");
$el.attr("muted", "true");
if (isWechat) {
// must play for wechat to enable this video.
$el.get(0).play();
$el.get(0).pause();
}
this.add($el);
}, this));
};
Player.prototype.add = function($el) {
var top = $el.offset().top;
var bottom = top + $el.height();
this.videos.push({
top: top,
bottom: bottom,
$el: $el,
});
};
Player.prototype.scrolled = function() {
var $window = $(window);
var top = $window.scrollTop();
var bottom = top + $window.height();
$.each($.map(this.videos, function(obj, i) {
var percent = 0;
if (obj.top <= bottom && obj.bottom >= top) {
var h = obj.bottom - obj.top;
if (obj.bottom > bottom) {
percent = (bottom - obj.top) / h;
} else if (obj.top < top) {
percent = (obj.bottom - top) / h;
} else {
percent = 1;
}
}
return {
percent: percent,
$el: obj.$el,
};
}), function(i, obj) {
if (obj.percent > 0.75) {
obj.$el.get(0).play();
} else {
obj.$el.get(0).pause();
}
});
};
Player.prototype.resized = function() {
$.each(this.videos, function(i, obj) {
obj.top = obj.$el.offset().top;
obj.bottom = obj.top + obj.$el.height();
});
this.scrolled();
};
Player.prototype.listen = function() {
var $window = $(window);
$window.on('scroll', $.proxy(function() {
if (this.videos.length) {
this.scrolled();
}
}, this));
$window.on('resize', $.proxy(function() {
if (this.videos.length) {
this.resized();
}
}, this));
};
$(document).ready(function() {
if (isWechat) {
document.addEventListener("WeixinJSBridgeReady", function () {
var player = new Player($("video"));
player.listen();
}, false);
} else {
var player = new Player($("video"));
player.listen();
}
});
})(jQuery, document, window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment