thelounge/client/js/libs/jquery/stickyscroll.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-12-18 16:53:28 +01:00
import jQuery from "jquery";
2014-07-05 02:31:20 +02:00
(function($) {
2016-04-17 12:50:03 +02:00
$.fn.unsticky = function() {
return this.trigger("unstick.sticky").unbind(".sticky");
2016-04-17 12:50:03 +02:00
};
2016-04-17 12:50:03 +02:00
$.fn.sticky = function() {
2014-07-05 02:31:20 +02:00
var self = this;
2016-04-17 12:50:03 +02:00
var stuckToBottom = true;
var lastStick = 0;
2016-04-17 12:50:03 +02:00
var keepToBottom = function() {
if (stuckToBottom) {
self.scrollBottom();
}
};
$(window).on("resize.sticky", keepToBottom);
2016-04-17 12:50:03 +02:00
self
.on("unstick.sticky", function() {
$(window).off("resize.sticky", keepToBottom);
2016-04-17 12:50:03 +02:00
})
.on("scroll.sticky", function() {
// 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) {
2016-04-17 12:50:03 +02:00
self.scrollBottom();
} else {
stuckToBottom = self.isScrollBottom();
2016-04-17 12:50:03 +02:00
}
})
.on("scrollBottom.sticky", function() {
stuckToBottom = true;
lastStick = Date.now();
this.scrollTop = this.scrollHeight;
})
.on("msg.sticky", keepToBottom)
2016-04-17 12:50:03 +02:00
.scrollBottom();
return self;
2014-07-05 02:31:20 +02:00
};
$.fn.scrollBottom = function() {
this.trigger("scrollBottom.sticky");
2016-04-17 12:50:03 +02:00
return this;
2014-07-05 02:31:20 +02:00
};
2016-04-17 12:50:03 +02:00
$.fn.isScrollBottom = function() {
var el = this[0];
return el.scrollHeight - el.scrollTop - el.offsetHeight <= 30;
2014-07-05 02:31:20 +02:00
};
})(jQuery);