Skip to content
This repository has been archived by the owner on Apr 5, 2020. It is now read-only.

How to use scrollspy after a dom element changed height? #5

Open
Cipa opened this issue Aug 23, 2012 · 2 comments
Open

How to use scrollspy after a dom element changed height? #5

Cipa opened this issue Aug 23, 2012 · 2 comments

Comments

@Cipa
Copy link

Cipa commented Aug 23, 2012

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

@guyisra
Copy link

guyisra commented Jun 8, 2013

+1

@artemgordinskiy
Copy link

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 :)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants