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

Is there a way to showcase XML in a web browser while maintaining its whitespace and preserving its preformatted text?

In an attempt to simplify the process of formatting my reports, I am considering creating a basic XML language. This would resemble something like this: <?xml-stylesheet href="./report.css"?> <report> <title>A Tale of Two Cities</ ...

Is there a way to retrieve a specific item from an array using a different method than just its position with jsRender?

I am currently working on rendering JSON data using jsRender. Take a look at the sample JSON data below: "PageContentList": [ { "ContentId": 51, "Title": "60 seconds with Rick", "ContentMediaTypeList": [ { ...

Tips for including arguments in pm2 file execution

What steps should I take to run the cluster.js file on pm2 successfully? When I try executing the file locally with 'node cluster.js 0 1' command, it appends two arguments but encountering an error when using 'pm2 start "cluster.js 0 1"&apos ...

A guide on utilizing the editUrl property in jQgrid with jQuery

Trying to implement dynamic edit/add of rows in jqgrid but facing issue with the editUrl attribute. Can someone please advise on: 1) Should the php file be kept in the server or within our application? 2) Currently using editurl: './data_save.php&ap ...

Baffled by the data visualization produced by Google Chart using information from

Perhaps I'm being a bit ambitious, but I managed to create a basic Chart using GoogleCharts. The problem is that I have to input the values manually, but I want to retrieve them from the Database. I know JSON can accomplish this, but I've spent f ...

What is the most effective way to share data among components in React?

I recently delved into learning about react and find myself puzzled on how to pass data between two components. Presently, I have set up 2 functions in the following manner: First, there's topbar.tsx which displays information for the top bar, inclu ...

Utilizing Ymacs in combination with Filepicker.io, incorporating ajax requests to fetch the desired content

I have been using Ymacs with Filepicker.io from this source and am attempting to fetch the content div through ajax calls. However, I'm facing an issue where I can't load the jQuery library as it leads to conflicts, resulting in the ajax not fun ...

Utilize jQuery to load portions of a webpage.onreadystatechange with jQuery

Here is the issue I am facing with loading content using jQuery: <nav id="side-nav"> <ul> <li><a href="consulting">Consulting</a></li> etc.. My jQuery code snippet is as follows: $(document).ready(function() { $( ...

StartsWith() function failing when used in conjunction with takeWhile()

I'm trying to iterate over an Immutable List and create a new list containing only the entries that start with a specific string. In this case, I want to find all states that begin with the letter 'D'. However, instead of returning a list wi ...

AngularJS restricts the display of elements to only 4 using the limitTo filter

I'm facing an issue with my filters. I have a JSON dataset that I need to display on my website, but I only want to show 4 elements that meet a certain criteria. Here's the code snippet: <div ng-repeat="place in places | limitTo: 4 | filter: ...

Creating a dynamic columns property for Mat-Grid-List

Is it possible to create a Mat-Grid-List where the number of columns can be dynamically changed based on the width of the container? Here is an example: <mat-grid-list [cols]="getAttachmentColumns()" rowHeight="100px" style="width: 100%;"> <mat ...

Creating a dropdown menu with jQuery

I need assistance in creating a <select> list using jQuery. This is my current attempt: $('<select />') .attr('name', 'location') .val("Location 1") .appendTo(this); Despite setting the value to .val( ...

Implementing a method to pass total value to the <td> tag in angular JS using controller

I am having trouble calculating the total IR for each table cell. Despite my efforts, the function is not working as expected and I can't figure out why. $scope.getTotalb = function () { var totalb = 0; for (var i = 0; i < $scope ...

What causes the conflict between Nodejs usb module and Electron?

Apologies for the lengthy post, but I've been tirelessly searching for a solution online without any luck. My goal is to create a basic Electron application that can display an HTML page (which is working fine) and control a printer through the USB mo ...

Exploring the wonders of jquery's JSON parsing capabilities

Having trouble parsing the JSON data that is out of my control. Can anyone help me figure out what I'm doing wrong here? data.json { "img": "img1.jpg", "img": "img2.jpg", "size": [52, 97] } { "img": "img3.jpg", "img": "img4.jpg", "size ...

Tips for generating a dynamic Array name to be sorted with React JS

My lack of experience is causing some issues for me. I am currently working on a form in react where the user has to select two values first. Based on these two values, a third value will be available for selection. However, the options for this third val ...

Utilize jQuery to target elements containing more than one class

Suppose an element has several classes as shown below: class="btn btn-primary add-movie-button is-on" Is it possible to select this element using only one class name with jQuery, for example: $(".add-movie-button") Can the method .hasClass("is-on") be ...

Is it possible for a function to alter the 'this' object in JavaScript?

Referencing the MDN article on this keyword in JavaScript When not in strict mode, 'this' in a function will point to the global object. However, attempting to modify a global variable within a function does not result as expected. Is there an ...

The data type 'string[]' cannot be assigned to the data type '[{ original: string; }]'

I have encountered an issue while working on the extendedIngredients in my Recipe Interface. Initially, I tried changing it to string[] to align with the API call data structure and resolve the error. However, upon making this change: extendedIngredients: ...

IE/Firefox returning empty value for Ajax requests

After spending two days trying to solve the issue, I still can't figure out why this code is failing in IE (v11) and Firefox while working fine in Chrome. I have read many questions on similar topics involving caching problems with multiple Ajax call ...