Last active
August 9, 2018 01:11
-
-
Save jiulongw/c42b2364b8f51538ac8934e79031f7b1 to your computer and use it in GitHub Desktop.
auto play mobile videos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($, document, window) { | |
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"); | |
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).on('ready', function() { | |
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