Merge pull request #346 from maxpoulin64/sticky-fix

Keep chat stickied to the bottom on resize
This commit is contained in:
Pavel Djundik 2016-06-05 11:31:04 +03:00
commit b6fa4471ab

View File

@ -1,29 +1,48 @@
(function($) { (function($) {
$.fn.unsticky = function() { $.fn.unsticky = function() {
return this.unbind(".sticky"); return this.trigger("unstick.sticky").unbind(".sticky");
}; };
$.fn.sticky = function() { $.fn.sticky = function() {
var self = this; var self = this;
var stuckToBottom = true; var stuckToBottom = true;
var lastStick = 0;
var keepToBottom = function() {
if (stuckToBottom) {
self.scrollBottom();
}
};
$(window).on("resize.sticky", keepToBottom);
self self
.on("scroll.sticky", function(e) { .on("unstick.sticky", function() {
stuckToBottom = self.isScrollBottom(); $(window).off("resize.sticky", keepToBottom);
}) })
.on("msg.sticky", function() { .on("scroll.sticky", function() {
if (stuckToBottom) { // When resizing, sometimes the browser sends a bunch of extra scroll events due to content
// reflow, so if we resized within 250ms we can assume it's one of those. The order of said
// events is not predictable, and scroll can happen last, so not setting stuckToBottom is
// not enough, we have to force the scroll still.
if (stuckToBottom && Date.now() - lastStick < 250) {
self.scrollBottom(); self.scrollBottom();
} else {
stuckToBottom = self.isScrollBottom();
} }
}) })
.on("scrollBottom.sticky", function() {
stuckToBottom = true;
lastStick = Date.now();
this.scrollTop = this.scrollHeight;
})
.on("msg.sticky", keepToBottom)
.scrollBottom(); .scrollBottom();
return self; return self;
}; };
$.fn.scrollBottom = function() { $.fn.scrollBottom = function() {
var el = this[0]; this.trigger("scrollBottom.sticky");
this.scrollTop(el.scrollHeight);
return this; return this;
}; };