I want to scroll smoothly by clicking on the sidebar link in jquery.

Asked 2 years ago, Updated 2 years ago, 44 views

See jsfiddle.—https://jsfiddle.net/ac189xhn/

Create a two-page page that contains the main content and the sidebar.
I want to be able to smoothly scroll to the section tag with the same main content as the id in the href when I click on the sidebar link, but now I scroll to an unexpected place when I click the same link twice or after the second time.

No matter how many times you click on the same link, it stays in the same place, and when this occurs, we could infer that the value obtained by destination.offset().top below is not the distance from the top of the parent element, but from the top of the browser screen.

$(".content").animate({
        scrollTop —destination.offset().top,
    },
    "slow"
);

I understand that, but how can I behave correctly?

javascript html jquery

2022-09-30 11:49

1 Answers

I solved myself.
varsh=$(".content").scrollTop();
Obtain the current location of the element to scroll to, and then
By adding destination.offset().top to the destination element, the behavior was correct.
Resolved jsfiddle↓
https://jsfiddle.net/zok428uq/

 function scrollToAnchor(aid){
        const destination=$("section[id='"+aid+"]");
        varsh=$(".content").scrollTop();
        $(".content").animate({
                scrollTop —destination.offset().top+sh,
            },
            "slow"
        );
    }

    $(document).on("click", ".sidebara", function(){
        varanchor=this.hash.replace("#", "");
        scrollToAnchor(anchor);
    });


2022-09-30 11:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.