Search code examples
javascriptjqueryonscrollonscrolllistener

jquery function destroy on scroll event


I have build so far a jquery function that stick html element to the top of the page when scrolling but destroy on scroll event is not working. I know that i should store the function for scroll event in variable but i dont know how to destroy it later. Can someone help me? This is my code so far:

(function ( $ ) {

$.fn.sticky = function(data) {
    var settings = $.extend({
        parent: null,
        offsetTop: 0,
        offsetBottom: 0,
        fixBottom: true,
        destroy: false
    }, data );

    this.each(function() {
        var elm = $(this),
        parent = $(settings.parent);

        if(settings.parent === null) {
            parent = elm.parent();
        }

        var elmTop = elm.offset().top,
            elmLeft = elm.offset().left,
            elmWidth = elm.width(),
            elmHeight = elm.height(),
            parentTop = parent.offset().top,
            parentHeight = parent.outerHeight(true),
            offs = elmTop - settings.offsetTop,
            margin_top = elmTop - parentTop,
            margin_bottom = parentHeight - elmHeight - margin_top,
            diff = parentHeight - elmHeight + parentTop - settings.offsetTop - settings.offsetBottom;

        var sticky_elm = function() {

            var w_top = $(window).scrollTop();

            if(w_top > offs && w_top < diff) {
                elm.attr("style", "position: fixed; top: "+settings.offsetTop+"px; left: "+elmLeft+"px; margin-left: 0;");
                if(!elm.next('[data-sticket-controller]').length) {
                    elm.after('<div data-sticket-controller style="visibility: hidden; opacity: 0; position: relative; width: '+elmWidth+'px; height: '+elmHeight+'px;"></div>');
                }
            }
            else if(w_top >= diff) {
                if(settings.fixBottom) {
                    elm.attr("style", "position: absolute; bottom: "+settings.offsetBottom+"px; left: "+elmLeft+"px; margin-left: 0;");
                }
            }
            else {
                elm.removeAttr("style");
                elm.next("[data-sticket-controller]").remove();
            }
        }

        if(settings.destroy) {
            $(document).off("scroll", sticky_elm);
        }
        else {
            $(document).on("scroll", sticky_elm);
        }
    });
};

}( jQuery ));

Solution

  • An event namespace would be useful in this case since the event listener is on the $(document) itself, so I have updated the fiddle with event namespace and a unique identifier for each sticky element so that we can turn off the event listener at any time later as long as we have the sticky element ID.

    https://jsfiddle.net/c289wLe1/11/