Navigating to the Top of the Page

I am facing an issue with my webpage that is similar to the code provided below:

var btn = document.getElementById('test')
test.addEventListener("click", function(){
    window.scroll(0,0)
})
.wrap {
  overflow-y: scroll;
  position: absolute;
  left: 0;
  top: 0px;
  right: 0;
  bottom: 0;
}

.container {
  height: 1280px
}
button {
  margin-top: 500px;
}
<div class="wrap">
  <div class="container">
    <div>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sollicitudin consequat massa et rutrum. In vel nulla pulvinar, sagittis ligula nec, pellentesque ligula. Proin ut nisl nec metus pellentesque congue eget tincidunt lectus. Proin nibh felis, vulputate eget vehicula et, viverra et sem. Aenean ornare felis id eros tincidunt rutrum ac eu magna. Nullam eleifend sit amet sapien id commodo. Praesent et est sagittis, vehicula velit ac, vehicula turpis. Aenean vel erat sem. Integer id tellus nisl. Donec interdum aliquam arcu, ac sagittis sem eleifend non. Sed tincidunt, massa a consequat venenatis, diam metus sodales eros, ut rutrum diam sem nec nisi. Vestibulum mattis nisl eu nulla posuere, a porta ante commodo. Duis in mauris ex. Ut a leo suscipit, posuere nulla eget, tristique nisi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc finibus commodo nisl, sed aliquam odio condimentum in.

Mauris tincidunt neque quis gravida volutpat. Proin mi enim, rutrum a eleifend ut, bibendum non turpis. Curabitur iaculis turpis vitae magna scelerisque lacinia. Suspendisse interdum fringilla ex ut laoreet. Cras convallis leo est, id congue diam fringilla et. Nullam tristique elit in fermentum vestibulum. Vivamus varius vehicula mollis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In a ligula vitae odio scelerisque interdum. Integer sed dui magna. Morbi placerat turpis id sollicitudin mattis.

Praesent pharetra pulvinar diam, in tincidunt turpis tempus eget. Phasellus luctus luctus consectetur. Vivamus tempor tellus eu justo eleifend luctus. Sed euismod at nisi aliquam facilisis. Nam eleifend volutpat lacus eu ornare. Ut fermentum dui eget tortor scelerisque venenatis. Vivamus pretium, justo id feugiat scelerisque, arcu ligula venenatis ante, nec maximus turpis elit et dui. Cras eget risus nulla. Vestibulum feugiat diam non viverra posuere. Nam ex sem, commodo volutpat sodales vel, euismod id sem.

Fusce ultrices semper ligula, quis mattis dolor blandit sit amet. Nulla placerat pharetra sem. Nulla vulputate placerat diam, sit amet convallis elit vulputate sed. Praesent scelerisque est sed orci gravida varius. Aenean non tellus lobortis, pretium nisl ultricies, semper diam. Vivamus non lectus a metus dictum varius. Praesent vehicula sodales sodales. Aliquam et nisi a ipsum viverra mollis. Sed aliquam ac lacus et laoreet. Morbi gravida sem vitae commodo semper. In hac habitasse platea dictumst. Quisque a ultricies sapien. Maecenas condimentum tellus tellus, eget pretium nulla lobortis consequat. Nam posuere malesuada dolor.

Pellentesque malesuada sapien ut sagittis porta. Maecenas eget lorem in nibh tristique euismod pretium at magna. Nulla posuere bibendum consequat. Curabitur pharetra elementum tellus, eget fringilla eros vestibulum quis. Sed varius ac tortor at cursus. Nulla facilisi. Pellentesque non elit vel metus bibendum imperdiet. Nullam venenatis luctus tellus. Maecenas sed molestie risus. Quisque in est in lectus euismod pretium.
    </div>
<div>
<button id="test">
Click me To Top
</button>
</button>
</div>
  </div>
  
</div>

Upon clicking the button on the page, I was expecting the scroll to move to the top of the screen, however, it does not work as intended. I am looking for a solution using vanilla javascript.

Answer №1

The issue arises from the CSS property position:absolute applied to your content, causing it to exist in a separate layer independent of the main document flow, resulting in independent scrolling behavior.

Additionally, an extra </button> tag is present in both your HTML code and JavaScript logic references a variable named btn, but the event setup is on test.

Removing the unnecessary instruction and ensuring consistency in the variable naming within the JavaScript code will resolve the issue.

document.getElementById('test').addEventListener("click", function(){
    window.scroll(0,0);
})
.wrap {
  left: 0;
  top: 0px;
  right: 0;
  bottom: 0;
}

.container {
  height: 1280px
}
button {
  margin-top: 500px;
}
<div class="wrap">
  <div class="container">
    <div>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sollicitudin consequat massa et rutrum. In vel nulla pulvinar, sagittis ligula nec, pellentesque ligula. Proin ut nisl nec metus pellentesque congue eget tincidunt lectus. Proin nibh felis, vulputate eget vehicula et, viverra et sem. Aenean ornare felis id eros tincidunt rutrum ac eu magna. Nullam eleifend sit amet sapien id commodo. Praesent et est sagittis, vehicula velit ac, vehicula turpis. Aenean vel erat sem. Integer id tellus nisl. Donec interdum aliquam arcu, ac sagittis sem eleifend non. Sed tincidunt, massa a consequat venenatis, diam metus sodales eros, ut rutrum diam sem nec nisi. Vestibu...
    </div>
    <div>
      <button id="test">Click me To Top</button>
    </div>
  </div> 
</div>

Answer №2

If you have no issue utilizing the anchor for this purpose, feel free to use

<style>
.wrap {
    position: absolute;
    top: 0; right: 0; bottom: 0; left: 0;
}
.container {
    height: 1280px;
    overflow-y: scroll;
}
.scroll-top-btn {
    display: inline-block;
    margin: 40px 0;
    padding: 5px 15px;
    border: 1px solid #777;
    border-radius: 6px;
    text-decoration: none;
    color: #000;
}
</style>
<div class="wrap">
    <div class="container">
        <div id="myText">
            Start<br>Start<br>Start<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>
            abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>
            abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>
            abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>
            abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>
            abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>
            abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>abcde<br>End<br>End<br>End<br>
        </div>
        <div>
            <a class="scroll-top-btn" href="#myText">Click me To Top</a>
        </div>
    </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to schedule requests using rxjs at a specific time?

I am looking to schedule requests three times a day at specific times (8 AM, 12 PM, 4 PM). How can I effectively set this up? ...

Updating state based on input from a different component

I am attempting to modify the state of the page index in index.js from the Pagination component, Here is my index.js code: import useSWR from 'swr'; import { useState } from 'react'; const Index = ({ data }) => { const ini ...

I am restricted from using history with BrowserRouter in Typescript

Trying out React and decided to experiment with TypeScript. Code: import { BrowserRouter } from 'react-router-dom' import history from './utilities/history' ReactDOM.render( <BrowserRouter history={history}> <App /> ...

Is there a way to void a delayed input event?

After reading this How to delay the .keyup() handler until the user stops typing? post, we have grasped how to implement delays. However, is there any suggestion on how to cancel a delayed event? Take a look at this In the scenario given, I want nothing t ...

Aligning the icon within the div and adding a gap between each div

I'm fairly new to web design, specifically dealing with html and css, and I'm attempting to create something similar to the design in the following image: https://i.sstatic.net/Dy5F3.png My struggle lies in centering the fa-envelope-o icon both ...

Guide to stripping HTTP headers from a REST API request using JavaScript

Hey there! I'm currently working on extracting a specific part of the response from the {}. This information is retrieved from the gemini public database, and my goal is to retrieve only the content within the curly braces and store it as a string in ...

Tips for utilizing ngx-bootstrap typeahead in conjunction with an asynchronous HttpClient request

Currently, I'm facing a challenge in populating nxg-bootstrap typeahead with asynchronous results from a REST backend in Angular 4. The example provided on their website () demonstrates how to achieve this using mock observable data, but implementing ...

Filtering Out Elements from an Array with the Filter Method

How can I efficiently remove all elements from an array that match the values of subsequent unknown arguments? Here's my current approach: function destroyer(arr) { var arrayOfArgs = []; var newArray = []; for (var i = 0; i < arguments ...

Tips for Preventing Unnecessary Ajax Requests

What I require When a click event is triggered, a service call should be made only once. Use case Dropdown1 Dropdown2 Dropdown3 1. There are three dropdowns on the HTML page. 2. When Dropdown1 is called - an AJAX call is made only onc ...

UV mapping with Plane BufferGeometry in Three.js

I'm facing some challenges creating a buffergeometry plane, specifically with the uv coordinates. Despite following advice from Correct UV mapping Three.js, I can't seem to achieve the desired result. Below is the snippet of code for the uv coor ...

Angular.js, Yeoman, and Grunt are essential tools for front-end

I've been working on developing an AngularJS application using Yeoman. Everything was going smoothly until I decided to implement some unit tests. Whenever I try to run my unit tests using grunt, I keep encountering the following error: Warning: Tas ...

Iterating through a JavaScript object

Just starting out with JavaScript and trying to figure out how to iterate through a JSON result that has been converted into a JavaScript object. const url = 'https://api.mybitx.com/api/1/tickers?pair=XBTMYR'; fetch(url) .then(res => re ...

The addDays method cannot be used with date variables

Having two TextBoxes where I input 2 dates and try to retrieve an array of dates between them. Here is the code I'm using: $(".txtto").change(function () { var dates = new Array(); var dateto = new Date(); ...

Creating a responsive grid layout using Bootstrap while addressing placement problems

Seeking help with Bootstrap for creating this particular layout design. Any advice? https://ibb.co/F7mv5V6 I've attempted the following code snippet, but it appears to be incorrect (looking for a result similar to the image provided) <div ...

"The authentication scheme is unrecognized" - this is the message produced by Node-LinkedIn module

I am currently utilizing the node-linkedin npm package to authenticate and retrieve information about other users, such as their name, job title, company name, profile picture, and shared connections. While I am able to successfully receive and store the a ...

What causes webpack to require 4 seconds for compiling a barebones react / redux project?

I am troubled by the fact that it is still compiling my node_modules even though I have specifically excluded it. How can I investigate and understand what exactly is happening? The output in the console seems like random characters. Is there a way to conf ...

wrap text image not compatible with responsive layout

Plunker Link: https://plnkr.co/edit/kC9SPK2e7iy5OYhKpwOO?p=preview <html> <head> <link data-require="bootstrap@*" data-semver="4.1.3" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" /> ...

Using jQuery to handle multiple buttons with the same ID

Is there a way to address the issue of multiple buttons sharing the same id? Currently, when clicking on any button, it only updates the record with id=1. How can this problem be resolved? div id="ShowPrace"> <?php try { $stmt = $pdo->prepare(" ...

Implement a toggle feature for login and registration with jQuery

I am facing an issue with the show/hide model on my website. When I click the link associated with it, nothing happens. I want it to function in a way that when I click "Sign up," the register form is displayed and when I click "Login," the register form ...

How to Retrieve Correct JSON Data from Mongoose Query in Node.js

I am currently working on an express application that utilizes mongoDB as the database and handlebars as my server-side templating engine. Unlike many applications, I have chosen not to incorporate AngularJS or Ajax into my project. One of the challenges ...