The onload function in jQuery is not functioning properly when the page is refreshed

I'm just starting out with jquery and I have a simple project in mind. The idea is to have two pictures stacked on top of each other, but I want the page to start showing the second picture first (at a specific scroll point). Then as the user scrolls up, the first picture will appear. Here's an example of what the code might look like:

HTML:

!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <script type="text/javascript" src="jquery.js"></script>
</head>   
<body>
        <div id="mainPage" width="100%">
            <img  id="top" src="pic1.jpg" width="100%">
            <img  id="bottom" src="pic2.jpg" width="100%">
        </div>
</body>
    <script type="text/javascript" src="script.js"></script>
</html>

CSS:

body {
    margin: 0px;
    padding: 0px;
}

#top {
  display: block; 
}

#bottom {
  display: block; 
}

JavaScript

window.onload = function() {
 scroll(0, 2300);
}

My code works perfectly when the page is initially loaded, but it fails if the page is refreshed (probably due to caching). How can I ensure that the onload function also works after a page refresh? Thanks for your help.

Answer №1

Have you considered using this particular function with $(document).ready() while using jq?

$(document).ready(function(){
  $(window).scrollTop( 3000 );
});
$(window).unload(function(){
  $(window).scrollTop( 3000 );
})
body {
  margin: 0px;
  padding: 0px;
}
#top {
  display: block;
}
#bottom {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mainPage" width="100%">
  <img id="top" src="http://drkeyurparmar.com/wp-content/uploads/2015/02/dummy-article-img-1.jpg" width="100%">
  <img id="bottom" src="http://drkeyurparmar.com/wp-content/uploads/2015/02/dummy-article-img-1.jpg" width="100%">
</div>

Answer №2

load represents the moment when a page loads, while beforeunload signifies the moment just before refreshing the page

 $(window).on("load",function() {        
    scroll(0, 2300); 
});
 $(window).on("beforeunload",function() {        
    scroll(0, 2300); 
});

Answer №3

Seems like your code is working fine the first time, but you may need to manually delete the page cache.

Here are some options to try:

Include these meta tags in your head section and see if it helps:

<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Expires" content="-1">

If you prefer to control the cache deletion using JavaScript, you can create a simple function like this:

function deleteCache(){
   window.location = window.location.href+'?eraseCache=true';
}

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

Provide all information in a single entry rather than going through a list multiple times

My current process involves using AJAX to submit data to a script for updating my database. Although the process is usually straightforward, in this particular case, I have to iterate through a list of selectors to gather values when clicking the submit b ...

Update the form content with the new information when a change is made,

I am looking to convert the below script from using a submithandler to an onchange event Currently, I have a form with a select (list) that is triggered by a submit button. It loads the results into a div. However, I want to change it so that the form sub ...

What is the best way to display an SVG file in a React application?

I am trying to figure out how to upload an SVG file and display a preview in a React component. I attempted to convert the SVG file into a React component by using the DOMParser to parse the SVG-XML string into a Document Object, but it is not functionin ...

What steps can I take to avoid Vue.js overriding jQuery bindings within components?

After incorporating vue.js into an existing project and attaching the vue instance to the body tag with an ID of "app," everything seemed to be running smoothly. jQuery and Vue.js were cooperating well together. However, as soon as I started creating compo ...

Ways to ensure the bootstrap table header width aligns perfectly with the body width

I am having an issue with my bootstrap table where the header width is smaller than the body width because I set the table width to auto. How can I align the header and body widths? Here is a link to a plunker showcasing the problem. https://plnkr.co/edit ...

How would the input value change if the clock time changed?

I am working with dynamic inputs that allow me to add and delete rows with inputs. These inputs include material-ui timepickers, which have an icon of a clock next to the input field. When I click on the clock icon, a clock widget appears. However, the val ...

Put Jest to the test by testing the appendFileSync function

I am currently working on creating a test for appendfilesync function. When using a logger, I noticed that one line of code is not covered in my tests. Below is the code snippet I am referring to (please note that I am using tslog for logging purposes): ex ...

The method to permit a single special character to appear multiple times in a regular expression

I am currently working on developing a REGEX pattern that specifically allows alphanumeric characters along with one special character that can be repeated multiple times. The permitted special characters include ()-_,.$. For instance: abc_def is conside ...

I keep trying to retrieve a specific property from an object, but every time I do, it returns as undefined

I'm currently employing Javascript within a React component. My goal is to retrieve a specific property from an object. If I log this object out to the console as shown below: console.log("Engine: ", this.Engine); The output looks like th ...

Tips for preventing the use of eval when invoking various functions

Here's a snippet of code I've been using that involves the use of eval. I opted for this approach as it seemed like the most straightforward way to trigger various factory functions, each responsible for different web service calls. I'm awa ...

Hiding the initial parent SVG element in the list will also hide all subsequent SVG elements within each section, excluding the container

I encountered a strange issue with my code in the Next framework. When using getServerSideProps, I made a request to my api folder, which resulted in a simple JSON response. Everything seemed to be working fine. The content was displayed perfectly without ...

Accessing JSON files locally using JavaScript in IE and Firefox

I am a beginner in JavaScript and currently working on a small HTML page that will be run locally. I have a string in JSON format that I need to store and load as a file on the hard drive. I have managed to store the string using the following code snippe ...

Leveraging the navigator geolocation feature in tandem with reactors

Struggling to save geolocation variables position.coords.lat/long in a global scope. Check out this code: var GeoLoco = React.createClass({ lat: 0, long: 0, handler: function(position) { ...

The issue of AngularJS jQuery combination: scope model not being updated

Can anyone explain why the model is not updating immediately after the destroyElement() function ends in my simple model with jQuery effects attached to elements rendered inside ng-repeat? Check out the code on JSFiddle: http://jsfiddle.net/nEzpS/33/ HTM ...

Updating the value of an HTML table cell when the data in local storage is changed using JavaScript

In my JavaScript code, I have a function that retrieves data from an API and stores it in the browser's localStorage. The API fetches ETA data and saves it in localStorage using the key id_ETA (e.g., 12342_ETA). I want the values in the HTML table&a ...

Customize DataTables to show specific rows with unique cell content and styling

We are currently using the jQuery DataTables plug-in and have encountered some limitations. Despite overcoming two major challenges, we are now facing a third issue: Within our table, we need to include a distinct row that serves as a visual separator bet ...

Encountered an error while attempting to log in: TypeError: the property 'id' of null cannot be read

I am facing an issue with the login process, specifically getting a TypeError: Cannot read property 'id' of null error message. How can I debug and resolve this error? var cas = require('cas-client'); get_forward_url(function(forwardur ...

How can I prevent ajax loader from overlapping headers in jquery-datatables?

Currently, I am developing a web application that utilizes jQuery data tables to load data from the server side. One issue I have encountered is that when the data table first loads, the loader covers the headers, creating a visibility problem as depicted ...

What is the best way to format a pseudo-element to serve as the header for a paragraph?

We are utilizing Markdown (Kramdown) for generating a static website. When incorporating infoboxes, we can enhance paragraphs and achieve the following outcomes: {:.note .icon-check title="This is a title"} Lorem, ipsum dolor sit amet consectetur adipisici ...

What is the best way to allow wider list items to overflow their absolutely positioned container?

My challenge involves a list that is dynamically populated, and I require it to be wider than its absolutely-positioned parent (specifically a custom <select> element implementation). #wrapper { position: relative; border: 1px ...