Home > Enterprise >  Smooth scroll to top of page
Smooth scroll to top of page

Time:12-15

I have spent hours on this and being a newbie to JavaScript / JQuery I still don't know how to do the following:

I have a "back to top" anchor link, in the footer of my pages, which links to the header. I understand there is CSS code to make this a smooth scroll (slow) movement:

html {
  scroll-behavior: smooth;
}

But this does not work in Safari.

On the CSS Tricks website (https://css-tricks.com/snippets/jquery/smooth-scrolling/) it says there is a JavaScript alternative to the above CSS:

window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth'
});

But how or where do I add this to my link / page? I presume I would want top: 0,

My HTML is this:

<header id="top">.... </header>

<footer>
<a href="#top"><img  src="resources/arrow.svg"></a>
</footer>

UPDATE I've tried the following, but it doesn't work. Any ideas why?

<footer>
    <a href="#top" onclick="window.scroll({ top: 0, behavior: 'smooth' })"><img  src="resources/arrow.svg"></a>
</footer>

CodePudding user response:

Use the onclick-Event:

<header id="top">....</header>
<div style="background-color: red; height: 1200px"></div>
<footer>
  <a style="cursor:pointer;" onclick="window.scroll({ top: 0, behavior: 'smooth' })"><img  src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Feather-arrows-arrow-up.svg/24px-Feather-arrows-arrow-up.svg.png"></a>
</footer>

  • Related