What is the most effective method for resetting the scroll position of a browser when refreshing a page?

Portfolio Query

I am in the process of setting up a basic portfolio website. My navigation bar includes various links, one of which is labeled "About Me". Upon clicking this link, the page immediately jumps to a specific section with an element ID of #about-me, and the URL is updated to include #about-me at the end.

However, I have noticed that when I refresh the page, the URL remains unchanged, causing the page to load at the same position instead of scrolling back to the top. I suspect this issue may be related to browser caching but I am not entirely certain.

What would be the most effective method to address this situation correctly?

Potential Resolutions

  1. One approach could involve utilizing the jQuery .ready() function to invoke a script once the DOM has finished loading. This script could reset the scroll position by updating the window.location.href to the original source URL.

  2. Alternatively, considering disabling browser caching might resolve the problem. However, it is important to note that this action could have implications for other areas of the site that rely on caching for optimized performance.

Answer №1

I stumbled upon a rather straightforward solution to this issue, in case anyone was curious. By preventing the default behavior of the event, you can avoid the URL adding the hash at the end. However, it's important to note that after doing this, you'll need to incorporate some code to ensure smooth scrolling functions correctly. This is because stopping the default behavior will also affect the functionality of navigation links. Additionally, if you refrain from re-adding the hash at the end of the animate function, the page will reload and start at the top upon refresh.

According to W3schools:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  // Implement smooth scrolling for all links
  $("a").on('click', function(event) {

    // Ensure that this.hash has a value before overriding the default behavior
    if (this.hash !== "") {
      // Prevent the default anchor click behavior
      event.preventDefault();

      // Save the hash
      var hash = this.hash;

      // Use jQuery's animate() method for smooth page scroll
      // The optional number (800) indicates the duration in milliseconds to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Simply leave out this line of code to ensure the page refresh starts at the top
        window.location.hash = hash;
      });
    } // End if
  });
});
</script>
 <style>
body, html, .main {
    height: 100%;
}

section {
    min-height: 100%;
}
</style>
</head>
<body>

<a href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>

<div class="main">
  <section></section>
</div>

<div class="main" id="section2">
  <section style="background-color:blue"></section>
</div>

</body>
</html>

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

The performance of the Ionic app is significantly hindered by lagging issues both on Google

After starting to work with the ionic framework, I noticed a significant change in performance when testing an android app on Chrome for the first time. It was fast and responsive until I added a button that led to a screen with navigation bars, side men ...

Choose the option from the jQuery dropdown list based on the displayed text instead of the value

In continuation of my previous question on jQuery getting values from multiple selects together, I am working with a select list like this: <select name="access" class="change" id="staff_off" runat="server"> <option value="8192">Off< ...

What is the best approach to retrieve a username from a SQL database using AJAX within a Flask application

I have been attempting to retrieve the username column information from SQL using ajax, but only the username of the first ID is being returned. However, I need all usernames to be fetched. Below is the model: class users(db.Model): id=db.Column(db.I ...

Using Express.js to Serve Static Content on a Dynamic Route

I am working with the app.js code below; app.use(express.static(__dirname + "/public")); app.use("/example", express.static(__dirname + "/public")); app.engine("html", require("ejs").renderFile); app.get("/", (req, res) => res.render("index.ejs")); a ...

Is there a way to utilize ajax to retrieve the current post's taxonomy term?

I'm currently working on building a filter for a custom post type in Wordpress. My goal is to dynamically display more posts based on the user's selection from a dropdown menu. While I have successfully implemented this feature, the challenge lie ...

Accessing a factory from within another in AngularJS Ionic

My Ionic app has been developed with two separate factories: one called Api, which handles API calls, and another called LDB (local database), responsible for interacting with a local Sqlite database using the CordovaSqlite plugin. While each factory work ...

Tabulating with jQuery Arrays

I am facing an issue when trying to perform calculations with certain numbers. Here is the specific code snippet causing trouble: for (var key in week_total) { $("." + key).html(week_total[key]); } After running this code, I keep getting a value of N ...

The tab functionality in Bootstrap is malfunctioning

Struggling with implementing tab functionality on my navigation bar using Bootstrap. The tab links change the URL, but the content of the tabs doesn't update accordingly. I'm using Bootstrap 4 - do I need to add jQuery code to make this work? Wha ...

"Choose" with the icon permanently attached

I am looking to customize a select element to choose a month. I want the dropdown list to display only the name of the months (e.g., January, February). However, in the selected value box of the select element, I would like to show a FontAwesome icon repre ...

Centralized Title / Side-aligned Menu

Good day, I am in need of assistance with a menu layout for my website. My goal is to have the title centered with the menu flexed out to the sides, but I'm encountering some issues. The colors included are just for testing purposes and will be update ...

Utilizing an offline HTML file instead of a URL within Objective-C programming

Is there a way to modify this code to utilize an offline (bundled) file instead of the "http://5times9.com"? - (void)loadAddWeb { UIWebView *addWeb = [[UIWebView alloc] init]; NSURL *webURL = [NSURL URLWithString:@"http://5times9.com"]; NSURLRequest *we ...

Using a JavaScript variable inside a jQuery string

Does anyone have suggestions for what I may be doing incorrectly here? VIEW DEMO HTML Code <div id="usercurrentccbox"> <div class="cardChoice"> <label for="mastercard"></label> </div> </div> JQUERY Sc ...

Spartacus 3.3 - Unleashing the Full Potential of the Default Sparta Storefront Theme

Looking for advice on how to customize the default Spartacus Storefront theme (Sparta) by only overriding specific CSS vars. Any suggestions? I tried following the instructions provided at: https://github.com/SAP/spartacus/blob/develop/projects/storefront ...

Is a function repeatedly invoked?

I have implemented a Pagination component in NextJS as follows: import Pagination from 'react-bootstrap/Pagination'; import Router from "next/router"; import {useEffect} from "react"; export { Paging } function Paging(props) ...

The onDrop event in javascript seems to be failing to execute

My attempts to get the javascript onDrop event to execute when an object is dropped into a drop zone have been unsuccessful. I've tried rewriting it in various ways without any success or error messages. In my search for potential reasons why the ondr ...

Adjust the input and transition the UI slider

Currently, I am facing an issue with two sliders and inputs. When the number in the top slider is changed, the number and slide in the bottom block do not update accordingly. What steps should I take to address this? $(document).ready(function() { var $ ...

The jQuery button that initially disappears when clicked to select all checkboxes

How can I make my button consistently visible when the page loads? I need a way to select and deselect all checkboxes with just one click. I've been struggling to find a solution. <!doctype html> <html> <head> <meta charset="utf ...

Tips for including headers with @Url.Action() to enable jwt authorization

When a user inputs correct login credentials, they should be redirected to the next page (LandingPage). However, upon clicking the Submit button, users are receiving a 401 unauthorized error instead of being directed to the next page. The JWT token is gene ...

change visibility:hidden to visible in a css class using JavaScript

I've put together a list of Game of Thrones characters who might meet their demise (no spoilers included). However, I'm struggling with removing a CSS class as part of my task. Simply deleting the CSS is not the solution I am looking for. I' ...

What happens when you add localhost# to the address bar using <a href="#"?

Playing around with jQuery to toggle visibility of divs on my local server. It works well on a test page, but when integrated into my PHP and HTML app, every time I use <a href="#" as a hook, it actually links to localhost/testsite/localhost# What c ...