0

So I have the following in my HTML page:

enter image description here

and i intentionally made it so that the "overflow" happens which results in the scrollbar at the right.

So i made a button called "Click to scroll up". So what i wanted was that everytime we click that button, the document would immediately scroll all the way up. Which means if I were to navigate all the way down, and click the button, it would bring me all the way up.

I looked up and there's a method "scrollTop" but it doesn't seemed to work. Would appreciate some help on this.

document.getElementById("scrollup").addEventListener("click", scrollUpmost);

function scrollUpmost() {
    $(document).scrollTop();
}
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html, body {
    height: 100%;
}

.container {
    border: 1px solid orange;
}

.big_div {
    border: 1px solid black;
    height: 1200px;

}

#scrollup {
    margin-top: 900px;
}
<!DOCTYPE html>
<html lang="en">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <div class = "big_div">
      <button id = "scrollup">Click to scroll up</button>
    </div>
  </div>
  <script src = "test.js"></script>
</body>
</html>
Maxxx
  • 3,688
  • 6
  • 28
  • 55
  • You do it simply by adding this line inside scroll function `window.scrollTo({ top: 0, behavior: 'smooth' }); ` – hashBender Jan 04 '21 at 05:55

1 Answers1

1

$("#scrollup").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});
    * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html, body {
    height: 100%;
}

.container {
    border: 1px solid orange;
}

.big_div {
    border: 1px solid black;
    height: 1200px;

}

#scrollup {
    margin-top: 900px;
}
  
<!DOCTYPE html>
<html lang="en">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  
  <div class="container">
    <div class = "big_div">
      <button id = "scrollup">Click to scroll up</button>
    </div>
  </div>
  <script src = "test.js"></script>
</body>
</html>

Please try this code

DVS
  • 326
  • 1
  • 7