2

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 class="to-top" 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 class="to-top" src="resources/arrow.svg"></a>
</footer>
user2991837
  • 626
  • 1
  • 8
  • 17

1 Answers1

7

Use the onclick-Event:

<header id="top">....</header>
<div style="background-color: red; height: 1200px"></div>
<footer>
  <a style="cursor:pointer;" onclick="window.scrollTo({ top: 0, behavior: 'smooth' })"><img class="to-top" src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Feather-arrows-arrow-up.svg/24px-Feather-arrows-arrow-up.svg.png"></a>
</footer>
Lars Flieger
  • 2,421
  • 1
  • 12
  • 34
  • Great this works, but is there a way to avoid using the button and simply use a link instead? The button inherits a lot of styling, looks awful and I'm not sure how to remove all the styling. – user2991837 Dec 14 '21 at 10:14
  • Is the onclick - event thingy JavaScript? I've not heard of global event handlers before – user2991837 Dec 14 '21 at 10:16
  • You can also use the anchor ``. Yes it's javascript. – Lars Flieger Dec 14 '21 at 10:20
  • Just tried it on the anchor and it doesn't work. See my updated post above – user2991837 Dec 14 '21 at 11:16
  • But this still doesn't work in Safari – user2991837 Dec 14 '21 at 17:24
  • @user2991837 Updated answer. scrollTo is supported by the major versions of safari. https://caniuse.com/?search=scrollTo – Lars Flieger Dec 14 '21 at 17:26
  • I can see from caniuse that it should work, but the smooth scrolling isn't working in my MacOS Safari most up to date version. It just instantly scrolls to the top. (Works in Chrome) I'm testing locally on my Mac. Would it make any difference if I uploaded it to my server? – user2991837 Dec 14 '21 at 17:37
  • @user2991837 Nope, that doesn't make a difference. I'll try on my MacBook and update you. EDIT: Safari is not supporting the option scroll smooth. (You can scroll but not smooth) Probably there is a workaround / polyfill needed: https://stackoverflow.com/questions/56011205/is-there-a-safari-equivalent-for-scroll-behavior-smooth – Lars Flieger Dec 14 '21 at 17:55