Is there a way to automatically scroll to the top on refresh or load without using Jquery in AngularJs or Js?

One issue I'm facing is trying to set the page to scroll to the top when it loads. However, Chrome, IE, and Firefox are currently resetting the scroll position to where it was on the previous page. How can I achieve this?

It appears that scrollTo doesn't work as expected in these browsers, despite trying various methods found on Stack Overflow. None of them seem to have any effect...

Any assistance would be greatly appreciated. Thank you all!

Answer №1

For anyone looking for a quick solution, here's something I stumbled upon right after posting my question (funny how that works sometimes):

window.onbeforeunload = function() {window.scrollTo(0,0);}

Edit: It seems like this code helps reset the browser's scroll position to the top before unloading the page, preventing it from remembering the last scroll position.

Answer №2

If you're looking for a solution, give this a shot:


<!DOCTYPE html>
<html>
<body onload="scrollToTop()">

<script>
function scrollToTop() {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
}
</script>

</body>
</html>

Hopefully this works for you :)

Answer №3

This is a vanilla JavaScript solution we've come up with. It incorporates a smooth easing effect to prevent jarring movements when the user clicks on the To Top button.

Despite its simplicity, this implementation is lightweight and becomes even smaller once minified. Developers seeking an alternative to the jQuery approach but aiming for similar outcomes may find this code snippet useful.

HTML

<button id="to-top">To Top</button>

JS

document.querySelector("#to-top").addEventListener("click", function(){

var toTopInterval = setInterval(function(){

    var supportedScrollTop = document.body.scrollTop > 0 ? document.body : document.documentElement;

    if (supportedScrollTop.scrollTop > 0) {
        supportedScrollTop.scrollTop = supportedScrollTop.scrollTop - 50;
    }

    if (supportedScrollTop.scrollTop < 1) {
        clearInterval(toTopInterval);
    }

}, 10);

 },false);

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

Setting the ng-class attribute on an AngularJS accordion-heading element seems ineffective

I'm encountering an issue with my accordion setup. Some entries in the accordion require a heading that highlights when there is a problem that needs attention. I attempted to use an "accordion-heading" with a conditional "ng-class" for "has-error" (t ...

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...

What is the method used to create the scrolling effect on this website?

I am in the process of creating my own personal website and I would like it to function similar to the following example: Instead of the typical scrolling, I'm interested in transitioning between different sections on the page. Could this be achieved ...

Looking to verify the presence of either key within an object using JavaScript

My goal is to determine whether at least one of the two specified keys exists in a particular object. let keys = ['foo', 'bar']; The object we are analyzing: let obj = { "foo": "value" } let obj1 = { "key& ...

Tips for utilizing the loadDataWithBaseURL() method to load CSS and JS files directly from an SDCARD

I am facing an issue with loading files from SDCARD onto a webview. The .html, .js, .css files are stored on the SDCARD in my scenario, and the html file content is encrypted. The steps I follow to load the html file are: Read file content Decrypt all co ...

Tips on activating the overlay solely on the image without affecting the entire column

Currently, I am working on a project locally and do not plan to release it. However, I am facing an issue with making the overlay only appear on the image rather than covering the entire column. I came across some pre-built code on the w3 schools website ...

How can I assign the items in a list as keys to an object in redux?

I am currently utilizing Redux in combination with Reactjs. The Redux Documentation states: It's recommended to return new state objects instead of mutating the existing state. My current object's state looks like this: state = [..., {id: 6 ...

Issue with fulfilling Ajax promises

How can I properly use a promise to compare the current logged-in user with a field from a list in SharePoint? function compareCurrentUserWithListObject() { var userProp = this._userProfileProperties; var userName = userProp.get_userProfilePropertie ...

The useRoutes function is returning null despite the correct pathname being provided

Check out my React code snippet! I've got the Component nestled within a micro-frontend application, which is then brought into the main app using module federation. // embedded in my microfrontend. const path = '/another-component-path'; f ...

The "a" HTML link element is stubbornly resisting being attached to an event listener

I have implemented the MutationObserver observer in my program to monitor the addition of elements. One specific condition I am checking for is if the added element is an anchor tag (tag="a") and if the link is a DOI, then I attach a contextmenu ...

Incorrect font displayed on Bootstrap button after inserting hyperlink

This section contains my HTML code snippet: <div class="panel panel-default"> <div class="panel-heading"> Records <button type="button" class="btn btn-xs btn-success pull-right" id="command-add" data-row-id="1"> ...

Unleashing the power of ::ng-deep to access CSS in an Angular child component

I'm attempting to modify the CSS class of a child component by using ::ng-deep. Despite my efforts with various iterations of the code provided below, I have been unsuccessful in accessing the CSS. The structure of the HTML component is depicted in th ...

Guide to creating the shared section of two wheels with CanvasRenderingContext2D

Is it possible to dynamically draw the shared area of two circular shapes using JavaScript and CanvasRenderingContext2D? My ultimate goal is to be able to adjust the size of the shape, ranging from a complete circle to a mere point. The desired outcome is ...

Tips for retrieving data from an external PHP resource that generates JSON output through Ajax?

Creating a PHP file to fetch the current time and date from the server through this link: <?php header('Content-Type: application/json'); $timezone = date_default_timezone_set("Asia/Manila"); $time = date("H:i:s A"); $date = date("m ...

Error message "Unable to access property 'rotation' of an object that does not exist - Three.js"

I'm currently facing an issue where my code is executing as expected, but there are two errors popping up in the console saying "Cannot read property 'rotation' of undefined". It's puzzling because both variables are defined globally. I ...

jQuery can be used to mask phone numbers with three input fields

I am looking to implement phone field masking using jQuery or JavaScript. I have tried a few jQuery mask plugins, but I am still searching for a better solution. Specifically, I need three input fields for the USA (it is a requirement). The inputs needed ...

Contrasting VSCode Live Server and Node Live Server

Recently delving into the world of JS, I've come across the need to set up a live server using npm. One popular extension in VSCode known as Live Server by Ritwick Dey caught my attention. I'm curious about the distinctions between utilizing this ...

Strange actions occurring within the $scope.$watch function

Below is the code snippet for my $scope.watch function: $scope.logChecked = []; $scope.selectAll = false; $scope.$watch('selectAll', function(selectAll) { console.log($scope.logChecked.length, $scope.logChecked, selectAll); }); The outp ...

reactjs with axios error message: "Error: Cannot read property 'map' of undefined"

I was experimenting with React and encountered an error while trying to parse JSON data from a localhost server instead of a local file. Despite searching for solutions in other posts, I haven't found a fix yet. I have installed the React Dev Tools ex ...

What is the best way to incorporate a feature that flips all choices in react-select?

I'm working with a multi-option Select component from react-select, and I need to add a special option that will invert the selected options into unselected ones, and vice versa. When this 'Invert selection' option is chosen, I don't w ...