Skip to content Skip to sidebar Skip to footer

Css/javascript Auto Scroll To Top

I am currently working on a simple (or so I thought) slide-down menu for both the desktop and mobile versions of a website I am working on. I'm trying to do this in CSS only if pos

Solution 1:

There may be some awkwardness in your idea that might just need a redesign, I certainly have never noticed a menu working like this.

But the jQuery code to scroll to the top is this:

$("html, body").animate({
    scrollTop: 0
}, 600);

Where 600 is how long it takes in ms. You'll have to wrap this in a click() function or something so it triggers when someone presses a menu option. For example:

$('#menu a').click(function () {
    $("html, body").animate({
        scrollTop: 0
    }, 600);
});

And of course all of this code should be wrapped in a $(document).ready() (basic jQuery setup) I know you didn't mention jQuery in your question, but this is a popular approach to solving problems like this.

Solution 2:

There is another way to achieve auto scroll on click using html only.

You just need to add an id to some div (the header maybe) and on the link you pass the #id to the href like so:

html

<divid="Header">your header</div><ahref="#Header">Go to the top</a>

css

/* Keyword values */
scroll-behavior: auto;
scroll-behavior: smooth;

I'd suggest to try out the scroll-behavior: smooth; it makes the transitions, well... smooth :D

Here you can find all the documentation you need about this solution https://developer.mozilla.org/de/docs/Web/CSS/scroll-behavior

Post a Comment for "Css/javascript Auto Scroll To Top"