jquery-scrollspy icon indicating copy to clipboard operation
jquery-scrollspy copied to clipboard

How to use scrollspy after a dom element changed height?

Open Cipa opened this issue 12 years ago • 2 comments

Hi,

Are there any tricks in making scrollspy work correctly after the height of an element changed after window load?

Thanks

I could provide an example

Cipa avatar Aug 23 '12 13:08 Cipa

+1

guyisra avatar Jun 08 '13 10:06 guyisra

Did anyone figure this out?

UPD: I didn't notice this at first, but turns out, scrollSpy accepts functions as "min" or "max" values. So this is what I ended up doing in the end:

MyApp: {
    mySection: $('#my-section'),

    scrollSpy: {
        init: function() {
            this.mySectionMinValue = 0;
            this.mySectionMaxValue = 0;

            this._initMySection();

            $(document).on('heightChange', $.proxy(this._resetHeights, this));
        },

        _initMySection: function() {
            MyApp.mySection.scrollspy({
                min: MyApp.scrollSpy.getMySectionMinValue,
                max: MyApp.scrollSpy.getMySectionMaxValue,
                onEnter: function() {
                    // do stuff
                },
                onLeave: function() {
                    // undo stuff
                }
            });

            return this;
        },

        getMySectionMinValue: function() {
            if (MyApp.scrollSpy.MySectionMinValue === 0) {
                MyApp.scrollSpy.MySectionMinValue = MyApp.MySection.offset().top;
            }

            return MyApp.scrollSpy.MySectionMinValue;
        },

        getMySectionMaxValue: function() {
            if (MyApp.scrollSpy.MySectionMaxValue === 0) {
                MyApp.scrollSpy.MySectionMaxValue = MyApp.MySection.offset().top + MyApp.MySection.height();
            }

            return MyApp.scrollSpy.MySectionMaxValue;
        },

        _resetHeights: function() {
            this.mySectionMinValue = 0;
            this.mySectionMaxValue = 0;
        }
    }
}

Then, when I change the height of the document, I simply trigger the "heightChange" event. So in the end, scrollSpy always has the latest min/max values and all is good :)

artemgordinskiy avatar Jan 24 '14 14:01 artemgordinskiy