Unable to scroll to the top of the page with JavaScript

I tried the code below but it didn't quite do the trick. Can someone assist me with refreshing the page to the top every time it loads?

window.addEventListener('load', function(){
   window.scrollTo(0,0)
})

window.onload = (event) => {
   window.scrollTo(0,0)
};

Answer №1

Your script is effective when the page does not load at the top

For instance, if a user clicks the back button or if the page loads with an ID in the URL hash

You have the option to eliminate the onload and instead include the script directly at the end of the page

window.addEventListener('load', function(){
   window.scrollTo(0,0)
})
div { height: 500px; background-color: yellow; }
<div>Div 1</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div id="x">Last Div</div>
<script>
 // mimicking the scenario where the page does not load at the top, unrelated to the answer
 document.getElementById("x").scrollIntoView(); //while loading
 
 // insert window.scrollTo(0,0) here if needed
 
</script>

Answer №2

Why not give this code a try instead of using window.scrollTo(0,0):

document.body.scrollTop = document.documentElement.scrollTop = 0;

Update your code to:

window.addEventListener('load', function(){
    document.body.scrollTop = document.documentElement.scrollTop = 0;
})

window.onload = (event) => {
   document.body.scrollTop = document.documentElement.scrollTop = 0;
};

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

utilize JavaScript on every element that has a specific identifier

<a id="link" href="http://www.google.co.uk">link</a> <a id="link" href="http://stackoverflow.com">link</a> Is there a way to make the JavaScript code apply to all <a> tags with the id="link", instead of just the first one? A ...

Exploring the process of transforming a dynamic PDF into a static PDF using PHP or NodeJS

Issue I am looking for a PHP/NodeJS API that can convert editable PDF files to non-editable PDFs online. Our client application requires the user to download PDF files that cannot be modified using software like Foxit Reader or Adobe. We are currently us ...

What is the method for concatenating two strings in JavaScript without any whitespace in between?

When working with two strings involving time, consider the following scenario: var gettime= $("#select-choice-2 :selected").text(); The above code returns a time value in 24-hour format, such as 17:45 However, if you require the time to display in the ...

Adjust the canvas size to fit its parent element ion-grid

I am currently working on an Ionic 3 component that displays a grid of images connected by a canvas overlay. I have utilized Ionic's ion-grid, but I am facing an issue with resizing the canvas. The problem is that I cannot determine the correct dimens ...

Using Selenium in JavaScript to upload an image is a straightforward process

I am trying to automate the process of uploading a picture using Selenium with the following script: driver.findElement(By.id(`avatar-upload`)).sendKeys(`/home/user/Desktop/smg935-0hero-0930.jpeg`) But I keep receiving this error: ElementNotInteractable ...

Grid Column with Checkboxes in Kendo UI for Vue

Seeking help in adding a checkbox column to a Kendo UI Vue grid. The column should display the values of a boolean field from the grid's data source. While I am aware of how to add a checkbox column for selection as demonstrated here: https://www.tele ...

bespoke HTML elements and properties

I'm currently facing some difficulties and I am unsure of how challenging it can be. I have tried following various tutorials, including those on SO and YouTube, but they all provide different approaches leaving me stuck. My goal is to create a custo ...

What is the best way to fill in the jquery treeselect widget?

I'm struggling with populating the jquery treeselect widget using a json file or any other method. Since I am new to jquery/javascript, I'm sure I must be missing some basics. Although I have obtained the plugin from https://github.com/travist/j ...

`18n implementation in Node.js and front-end JavaScript for localization`

I am currently utilizing express js 4.0 and have set up the i18n module from https://github.com/mashpie/i18n-node in combination with ejs views. My goal is to extend this i18n functionality to .js files as well. Is there a way to enable the i18n function ...

What is the best way to display JSON data in a readable format?

I received a JSON file with the following structure: { "data":{ "uuid":"123", "name":"TestData", "alias":null, "created_at":"2021-03-17T11:57:29.000000Z&q ...

Using Axios to retrieve data from a MySQL database is a common practice in web development. By integrating Vue

I have developed another Vue.js admin page specifically for "writer" where I can display post data fetched from a MySQL database. The admin page called "admin" is functioning properly and responding with all the necessary data. The following code snippet ...

The variable remains undefined, despite the fact that the code executes correctly in a different location

I'm currently working on a multiplayer game in three js and integrating socket.io for real-time communication. I have all the player characters stored in an array called players on the server side. When each client connects, I send them the list of p ...

What is the best way to transfer a JavaScript variable value from an HTML page to a Model variable within the controller?

I'm facing a challenge in my HTML page where I need to pass a variable value from the frontend to a Model class in an MVC project. What is the most efficient way to achieve this with minimal code? Here's what I have attempted: Index.cshtml: v ...

Resources for Vue.js stylesheets

Vue.js is my latest discovery and I have been experimenting with the single file component architecture. A small issue I encountered was that all of my components' styles were being loaded on the page, even if they weren't currently active. Is t ...

Tips on ensuring data cleanliness in jQuery input fields

Before sending the ajax request, I want to sanitize the form fields for added security. Currently, my Javascript code looks like this: jQuery(document).ready(function($) { $('#login-form').submit(function(e) { e.preventDefault(); // pr ...

Iterate over the HTML elements within a class and retrieve a specific property in JSON

Currently, I am in the process of developing a straightforward application that involves making an Ajax request to retrieve a Json object and then passing it to an HTML document. Essentially, this application functions as a vending machine where the produc ...

Can phantomJS be used to interact with elements in protractor by clicking on them?

While attempting to click a button using PhantomJS as my browser of choice, I encountered numerous errors. On my first try, simply clicking the button: var button = $('#protractorTest'); button.click(); This resulted in the error: Element is ...

Guide to placing the Drawer component beneath the AppBar in Material-UI

Exploring the capabilities of the Material UI drawer component, I'm looking to position the drawer below the appbar. My goal is to have the hamburger icon toggle the drawer open and closed when clicked: opening the drawer downwards without moving the ...

What is the process for reverting back to a previous version using n (Node Version Manager)?

After installing n(tj/n) to manage my node versions, I installed Node version 14.6 which automatically became the active version. When I tried to switch back using the n command, it only displayed the version I installed with n. Is there a way to switch b ...

Using React.js to Retrieve Data from the Server without AJAX Calls

Currently, I am in the process of creating a web application using Express.js for the back-end and React.js for the front-end. Prior to using React.js, I utilized EJS templating and followed a similar workflow on the back-end as shown below: var express = ...