Search code examples
javascriptjqueryresizeoffset

update my offset().top value on window resize


i have 4 offset().top values that i would like updated when i resize the page. i have each value stored as a variable to use with a scrolling animation and css style changes as you scroll down. here is a bit of the code:

    var top1 = $('#home').offset().top;
    var top2 = $('#profile').offset().top;
    var top3 = $('#portfolio').offset().top;
    var top4 = $('#contact').offset().top;

    $(document).scroll(function () {
        var scrollPos = $(document).scrollTop();

        if (scrollPos >= top1 && scrollPos < top2) {
            $('.nav-bar').css({
                'background-color': 'rgba(255, 255, 255, 0.7)',
                'color': '#203B40'
            });


    $("#homeLink").click(function () {
        $("html, body").animate({
            scrollTop: top1
        }, 500);
    });
    $("#profileLink").click(function () {
        $("html, body").animate({
            scrollTop: top2 + 8
        }, 500);
    });

for now, if i manually refresh the page after resize everything matches up fine, on any size. However, if i change the page size without refreshing, the links no longer match up.

i have played around with $(window).resize and window.addEventListener('resize', function) but don't know how to properly use them. i have spent the last three nights scouring google and playing with (breaking) my code. Maybe I just need to reset my variable values on resize, or i have to reset the entire page. i am not sure the best way to deal with this.

here is my codepen with the code. i didnt add the photos or bg imgs. but all the code is there. Thanks for any and all help. https://codepen.io/efe-in-the-mountains/pen/dJLaqK?editors=0010


Solution

  • You need to change your top1,top2,top3,top4 variable when $(window).resize is triggered. Add the snippet below and see if the code is doing what I think you want to do.

      $(window).resize(function () {
                top1 = $('#home').offset().top;
                top2 = $('#profile').offset().top;
                top3 = $('#portfolio').offset().top;
                top4 = $('#contact').offset().top;
            });
    

    Read more here https://developer.mozilla.org/en-US/docs/Web/Events/resize to understand when the resize event is triggered.