Javascript – smooth scroll to top

javascript

I've bean searching for this for a few hours now and I have no solution. I want a smooth scroll to the top of the page. I already have smooth scrolling to separate anchors in the page with a .js file attatched to my site but I cannot use an anchor for the top, because I'm using a template from a free hosting site with built in page building tools that do not allow me to edit above the body area.

Here's where I got the smooth scrolling. I've been trying to set up "smoothly-scroll-to-an-element-without-a-jquery-plugin" but I have no idea how to arrange it obviously after countless attempts. I've also used window.scrollTo(0, 0); but it scrolls instantly. Thanks!

In addition:
http://jsfiddle.net/WFd3V/ – the code would probably be the tag class="smoothScroll" since my other element uses that, but I don't know how to mix it with the href="javascript:window.scrollTo(0,0);" , or anything else that would bring the page to the top without an anchor.

Best Answer

I think the simplest solution is:

window.scrollTo({top: 0, behavior: 'smooth'});

If you wanted instant scrolling then just use:

window.scrollTo({top: 0});

Can be used as a function:

// Scroll To Top

function scrollToTop() {

window.scrollTo({top: 0, behavior: 'smooth'});

}

Or as an onclick handler:

<button onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Scroll to Top</button>