KingNestor
KingNestor

Reputation: 67950

Scroll to the top of the page using JavaScript?

How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I'm not looking to achieve smooth scrolling.

Upvotes: 2071

Views: 2526610

Answers (30)

Ahmad Moghazi
Ahmad Moghazi

Reputation: 1705

Smooth scrolling & animation with vanilla Javascript, without jQuery

// Get the element
let topBtn = document.querySelector(".top-btn");

// On Click, Scroll to the page's top, replace 'smooth' with 'instant' if you don't want smooth scrolling
topBtn.onclick = () => window.scrollTo({ top: 0, behavior: "smooth" });

// On scroll, Show/Hide the btn with animation
window.onscroll = () => topBtn.style.opacity = window.scrollY > 500 ? 1 : 0;
body {
  background-color: #111;
  height: 5000px;
  font-size:5rem;
  color: white;
}

.top-btn {
  all: unset;
  font-size:1.5rem; 
  position: fixed;
  right: 20px;
  bottom: 20px;
  cursor: pointer;
  transform:scale(1.8);
  opacity: 0;
  transition: .3s;
}
<button class="top-btn">🔝</button>
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Quisque vel sem vel dui sodales cursus. Vivamus nec erat eu nisl facilisis laoreet vel a dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc vel elit eget mauris gravida dictum non at eros. Sed nec massa eu justo interdum fringilla. Fusce nec dolor auctor, tincidunt purus id, feugiat justo. Pellentesque tincidunt, mauris a dapibus eleifend, libero lorem congue elit, eget iaculis odio metus non mi." "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Quisque vel sem vel dui sodales cursus. Vivamus nec erat eu nisl facilisis laoreet vel a dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc vel elit eget mauris gravida dictum non at eros. Sed nec massa eu justo interdum fringilla. Fusce nec dolor auctor, tincidunt purus id, feugiat justo. Pellentesque tincidunt, mauris a dapibus eleifend, libero lorem congue elit, eget iaculis odio metus non mi." "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Quisque vel sem vel dui sodales cursus. Vivamus nec erat eu nisl facilisis laoreet vel a dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc vel elit eget mauris gravida dictum non at eros. Sed nec massa eu justo interdum fringilla. Fusce nec dolor auctor, tincidunt purus id, feugiat justo. Pellentesque tincidunt, mauris a dapibus eleifend, libero lorem congue elit, eget iaculis odio metus non mi." "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Quisque vel sem vel dui sodales cursus. Vivamus nec erat eu nisl facilisis laoreet vel a dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc vel elit eget mauris gravida dictum non at eros. Sed nec massa eu justo interdum fringilla. Fusce nec dolor auctor, tincidunt purus id, feugiat justo. Pellentesque tincidunt, mauris a dapibus eleifend, libero lorem congue elit, eget iaculis odio metus non mi." "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Quisque vel sem vel dui sodales cursus. Vivamus nec erat eu nisl facilisis laoreet vel a dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc vel elit eget mauris gravida dictum non at eros. Sed nec massa eu justo interdum fringilla. Fusce nec dolor auctor, tincidunt purus id, feugiat justo. Pellentesque tincidunt, mauris a dapibus eleifend, libero lorem congue elit, eget iaculis odio metus non mi."</p>

With React.js

import { useEffect, useState } from 'react';

export default function ScrollToTop() {
  const [isVisible, setIsVisible] = useState(false);

  const handleScroll = () => setIsVisible(window.scrollY > 500);
  const scrollToTop = () => window.scrollTo({ top: 0, behavior: 'smooth' });


  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <button
      style={{
        all: 'unset',
        fontSize: '1.5rem',
        position: 'fixed',
        right: '20px',
        bottom: '20px',
        cursor: 'pointer',
        transform: 'scale(1.8)',
        opacity: isVisible ? 1 : 0,
        transition: '0.3s',
      }}
      onClick={scrollToTop}
    >
      🔝
    </button>
  );
}

Upvotes: 30

Dalex
Dalex

Reputation: 3061

All of these suggestions work great for various situations. For those who find this page through a search, one can also give this a try. JQuery, no plug-in, scroll to element.

$('html, body').animate({
    scrollTop: $("#elementID").offset().top
}, 2000);

Upvotes: 76

Lilia Martins
Lilia Martins

Reputation: 41

This works for me:

document.documentElement.scrollIntoView({ behavior: "smooth" })

Upvotes: 0

Aslam khan
Aslam khan

Reputation: 345

Try this solution using simple css just put css scroll-behavior:smooth on html and body as i have applied in css. that's it

document.querySelector('a').onclick = function() {
  window.scrollTo(0,0)
}
html,body{
  scroll-behavior: smooth;
}
a{
  background-color: red;
  color:#fff;
  border-radius: 10px;
  margin:10px 0;
  display: inline-block;
  padding:10px 20px;
}
<p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<a>Scroll to Top</a>

I Hope this will help you a lot. Please do let me know your thoughts

Upvotes: 4

lordisp
lordisp

Reputation: 730

Back to Top with AplineJS and TailwindCSS:

<button
    x-cloak
    x-data="{scroll : false}"
    @scroll.window="document.documentElement.scrollTop > 20 ? scroll = true : scroll = false"
    x-show="scroll" @click="window.scrollTo({top: 0, behavior: 'smooth'})"
    type="button"
    data-mdb-ripple="true"
    data-mdb-ripple-color="light"
    class="fixed inline-block p-3 text-xs font-medium leading-tight text-white uppercase transition duration-150 ease-in-out bg-blue-600 rounded-full shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg bottom-5 right-5"
    id="btn-back-to-top"
    x-transition.opacity
>
    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" viewBox="0 0 20 20" fill="currentColor">
        <path fill-rule="evenodd" d="M3.293 9.707a1 1 0 010-1.414l6-6a1 1 0 011.414 0l6 6a1 1 0 01-1.414 1.414L11 5.414V17a1 1 0 11-2 0V5.414L4.707 9.707a1 1 0 01-1.414 0z" clip-rule="evenodd" />
    </svg>
</button>

Upvotes: 2

willingdev
willingdev

Reputation: 9546

Scroll to top of page with animation:

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

Upvotes: 38

Rahul Daksh
Rahul Daksh

Reputation: 230

Please check the below code, surely it will be helpful. :)

document.querySelector('.sample-modal .popup-cta').scrollIntoView(true);
document.querySelector('.sample-modal').style.scrollPadding = '50px'; //to move to the top when scrolled up.

Upvotes: 0

Max S.
Max S.

Reputation: 1461

document.getElementsByTagName('html')[0].scrollIntoView({ behavior: "smooth" });

Upvotes: 4

object-Object
object-Object

Reputation: 1681

document.getElementById("elem").scrollIntoView();

Upvotes: 8

Sedki Sghairi
Sedki Sghairi

Reputation: 379

A simple example of scroll to (using html is much more efficient but here is how to do it with JavaScript):

const btn = document.querySelector('.btn');
btn.addEventListener('click',()=>{
      window.scrollTo({
       left: 0,
       top: 0,
})})
window.addEventListener('scroll', function() {
    const scrollHeight = window.pageYOffset;
    if (scrollHeight > 500) {
        btn.classList.add('show-link');
    } else {
        btn.classList.remove('show-link');
    }
});
.section {
    padding-bottom: 5rem;
    height: 90vh;
}
.btn {
    position: fixed;
    bottom: 3rem;
    right: 3rem;
    background: blue;
    width: 2rem;
    height: 2rem;
    color: #fff;
    visibility: hidden;
    z-index: -100;
}
.show-link {
    visibility: visible;
    z-index: 100;
}

.title h2 {
    text-align: center;

}
    <section class="section">
      <div class="title">
        <h2>Section One</h2>
      </div>
    </section>
    <section class="section">
      <div class="title">
        <h2>Section Two</h2>
      </div>
    </section>
    <section  class="section">
      <div class="title">
        <h2>Section Three</h2>
      </div>
    </section>
    <a class="btn">
    </a>

Upvotes: 1

SavoryBytes
SavoryBytes

Reputation: 36236

If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript window.scrollTo() method -- passing in 0, 0 will scroll the page to the top left instantly.

window.scrollTo(xCoord, yCoord);

Parameters

  • xCoord is the pixel along the horizontal axis.
  • yCoord is the pixel along the vertical axis.

Upvotes: 2716

Mehran Nasr
Mehran Nasr

Reputation: 307

There is no need to javascript, event if you wanted to animate the scroll action!

CSS:

html {
    scroll-behavior: smooth;
}

HTML:

<html>
  <body>
     <a id="top"></a>
     <!-- your document -->
     <a href="#top">Jump to top of page</a>
  </body>
</html>

Upvotes: 2

Smaillns
Smaillns

Reputation: 3127

The equivalent solution in TypeScript may be as the following

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

Upvotes: 17

Justin Liu
Justin Liu

Reputation: 621

You can use javascript's built in function scrollTo:

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

Upvotes: 7

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92347

Shortest

location='#'

This solution is improvement of pollirrata answer and have some drawback: no smooth scroll and change page location, but is shortest

Upvotes: 1

Kamlesh Kumar
Kamlesh Kumar

Reputation: 1680

<script>
$(function(){
   var scroll_pos=(0);          
   $('html, body').animate({scrollTop:(scroll_pos)}, '2000');
});
</script>

Edit:

$('html, body').animate({scrollTop:(scroll_pos)}, 2000);

Another way scroll with top and left margin:

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

Upvotes: 46

Saeed Hassanvand
Saeed Hassanvand

Reputation: 977

Pure JavaScript solution:

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

I write an animated solution on Codepen

Also, you can try another solution with CSS scroll-behavior: smooth property.

html {
    scroll-behavior: smooth;
}

@media (prefers-reduced-motion: reduce) {
    html {
        scroll-behavior: auto;
    }
}

Upvotes: 14

Rajkumar
Rajkumar

Reputation: 1077

Just Try, no need other plugin / frameworks

document.getElementById("jarscroolbtn").addEventListener("click", jarscrollfunction);

function jarscrollfunction() {
  var body = document.body; // For Safari
  var html = document.documentElement; // Chrome, Firefox, IE and Opera 
  body.scrollTop = 0; 
  html.scrollTop = 0;
}
<button id="jarscroolbtn">Scroll contents</button> 
html, body {
  scroll-behavior: smooth;
}

Upvotes: 2

Ganesh Ghalame
Ganesh Ghalame

Reputation: 7003

Better solution with smooth animation:

// this changes the scrolling behavior to "smooth"
window.scrollTo({ top: 0, behavior: 'smooth' });

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo#Example

Upvotes: 436

arvinda kumar
arvinda kumar

Reputation: 709

$(".scrolltop").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});
.section{
 height:400px;
}
.section1{
  background-color: #333;
}
.section2{
  background-color: red;
}
.section3{
  background-color: yellow;
}
.section4{
  background-color: green;
}
.scrolltop{
  position:fixed;
  right:10px;
  bottom:10px;
  color:#fff;
}
<html>
<head>
<title>Scroll top demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div class="content-wrapper">
<div class="section section1"></div>
<div class="section section2"></div>
<div class="section section3"></div>
<div class="section section4"></div>
<a class="scrolltop">Scroll top</a>
</div>

</body>
</html>

Upvotes: 20

Gianluca Casati
Gianluca Casati

Reputation: 3753

Motivation

This simple solution works natively and implements a smooth scroll to any position.

It avoids using anchor links (those with #) that, in my opinion, are useful if you want to link to a section, but are not so comfortable in some situations, specially when pointing to top which could lead to two different URLs pointing to the same location (http://www.example.org and http://www.example.org/#).

Solution

Put an id to the tag you want to scroll to, for example your first section, which answers this question, but the id could be placed everywhere in the page.

<body>
  <section id="top">
    <!-- your content -->
  </section>
  <div id="another"><!-- more content --></div>

Then as a button you can use a link, just edit the onclick attribute with a code like this.

<a onclick="document.getElementById('top').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })">Click me</a>

Where the argument of document.getElementById is the id of the tag you want to scroll to after click.

Upvotes: 8

Santosh Jadi
Santosh Jadi

Reputation: 1527

This will work:

window.scrollTo(0, 0);

Upvotes: 22

jeancallisti
jeancallisti

Reputation: 1663

None of the answers above will work in SharePoint 2016.

It has to be done like this : https://sharepoint.stackexchange.com/questions/195870/

var w = document.getElementById("s4-workspace");
w.scrollTop = 0;

Upvotes: 5

Gayashan Perera
Gayashan Perera

Reputation: 671

Simply use this script for scroll to top direct.

<script>
$(document).ready(function(){
    $("button").click(function(){
        ($('body').scrollTop(0));
    });
});
</script>

Upvotes: 7

Gaurang Sondagar
Gaurang Sondagar

Reputation: 834

If you want to do smooth scrolling, please try this:

$("a").click(function() {
     $("html, body").animate({ scrollTop: 0 }, "slow");
     return false;
});

Another solution is JavaScript window.scrollTo method :

 window.scrollTo(x-value, y-value);

Parameters :

  • x-value is the pixel along the horizontal axis.
  • y-value is the pixel along the vertical axis.

Upvotes: 30

Musaib Memdu
Musaib Memdu

Reputation: 71

When top scroll is top less than limit bottom and bottom to top scroll Header is Sticky. Below See Fiddle Example.

var lastScroll = 0;

$(document).ready(function($) {

$(window).scroll(function(){

 setTimeout(function() { 
    var scroll = $(window).scrollTop();
    if (scroll > lastScroll) {

        $("header").removeClass("menu-sticky");

    } 
    if (scroll == 0) {
    $("header").removeClass("menu-sticky");

    }
    else if (scroll < lastScroll - 5) {


        $("header").addClass("menu-sticky");

    }
    lastScroll = scroll;
    },0);
    });
   });

https://jsfiddle.net/memdumusaib/d52xcLm3/

Upvotes: 1

Wasif Ali
Wasif Ali

Reputation: 894

Try this code:

$('html, body').animate({
    scrollTop: $("div").offset().top
}, time);

div => Dom Element where you want to move scroll.

time => milliseconds, define the speed of the scroll.

Upvotes: 11

Priyanka
Priyanka

Reputation: 31

For scrolling to the element and element being at the top of the page

WebElement tempElement=driver.findElement(By.cssSelector("input[value='Excel']"));

            ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", tempElement);

Upvotes: 0

mehmood
mehmood

Reputation: 2600

Try this to scroll on top

<script>
 $(document).ready(function(){
    $(window).scrollTop(0);
});
</script>

Upvotes: 216

Sriram
Sriram

Reputation: 787

You dont need JQuery. Simply you can call the script

window.location = '#'

on click of the "Go to top" button

Sample demo:

output.jsbin.com/fakumo#

PS: Don't use this approach, when you are using modern libraries like angularjs. That might broke the URL hashbang.

Upvotes: 8

Related Questions