Skip to content

Instantly share code, notes, and snippets.

@rc1021
Last active August 8, 2018 06:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rc1021/132efe751c58b19fcb611af90bf8690d to your computer and use it in GitHub Desktop.
Save rc1021/132efe751c58b19fcb611af90bf8690d to your computer and use it in GitHub Desktop.
指定 selector 如果有捲軸時,當滑動至底部時觸發事件

說明

指定 selector 如果有捲軸時,當滑動至底部時觸發事件

用法

require('./jquery-scroll-bottom');

// method 1
$('selector').scrollBottom({
    closure: function (event) {
        // console.log(event.target); // the selector
        // console.log("到達底部時此方法會被呼叫");
    }
});

// method 2: or another method(init)
$('selector').scrollBottom().on("has.reached", function (event) {
    // console.log(event.target); // the selector
    // console.log("scrollBottom 另一種到達底部時會被呼叫的方法");
});
/**
* @description jQuery-scroll-bottom。
*
* 指定 selector 如果有捲軸時,當滑動至底部時觸發事件
* @module ScrollBottom
* @author 許益銘 <mufasa.hsu@gmail.com>
* @example
* require('./jquery-scroll-bottom');
*
* // method 1
* $('selector').scrollBottom({
* closure: function (event) {
* // console.log(event.target); // the selector
* // console.log("到達底部時此方法會被呼叫");
* }
* });
*
* // method 2: or another method(init)
* $('selector').scrollBottom().on("has.reached", function (event) {
* // console.log(event.target); // the selector
* // console.log("scrollBottom 另一種到達底部時會被呼叫的方法");
* });
*/
// main function
function enableScrollBottom (options) {
function onScroll(event) {
if($(event.target).prop('scrollHeight') - ($(event.target).innerHeight() + $(event.target).prop('scrollTop')) <= 0) {
if(typeof $(event.target).data('closure') === "function") {
$(event.target).data('closure').call(event.target, event);
}
$(event.target).trigger("has.reached");
}
}
if(options === "destory") {
this.off("scroll", onScroll);
}
else {
this.data(options||{}).on("scroll", onScroll);
}
return this;
}
// extend "scrollBottom" to $.fn
(function ($) {
if(typeof $.fn.scrollBottom !== "function") {
$.fn.extend({
scrollBottom: enableScrollBottom
});
// auto initialize
$(function () {
$('[data-rel="scroll-bottom"]').scrollBottom();
})
}
})(jQuery || $);
module.exports = function (instance, options) {
enableScrollBottom.call(instance, options || {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment