What causes the scrollTop to appear erratic?

There is a simple issue that I find difficult to explain in text, so I have created a video demonstration instead. Please watch the video at this link:

The functionality on my page works perfectly when scrolling down, as it replaces images with the next image in the series.

However, the problem arises when I stop scrolling – the image reverts back to an earlier one. I have been monitoring the value of scrollTop (which is logged in the console in my video), and it seems that at the end of scrolling (when I release my fingers from the mousepad), it returns a low value such as 0.

Why is this happening? All I want is for the image to stay in place once I lift my fingers from the scroll wheel or pad.

Below is the code snippet that I am using:

<html>
<meta charset="UTF-8">
<head>
<script type="text/javascript">
    var lastScrollTop;
    function mainScript(){
        bgResize();
        lastScrollTop = document.body.scrollTop;
        window.addEventListener("scroll", bgAnimation, false);
        window.addEventListener('resize', bgResize);
    }

    function bgAnimation(){

        var currentScrollTop = document.body.scrollTop;
        var currentBg = document.getElementById("pictureAnimation").src;
        var currentBgNum = currentBg.substring(currentBg.length-8, currentBg.length-4);
        console.log(lastScrollTop);


        if(currentScrollTop > lastScrollTop){
            if((currentBgNum < 0196) && (currentBgNum > 99)){
                var nextBgNum = Number(currentBgNum)+1;

                nextBgNum = String("0" + nextBgNum);
                var nextBg = currentBg.replace(currentBgNum, nextBgNum);
                document.getElementById("pictureAnimation").src = nextBg;
                lastScrollTop = currentScrollTop;
            }
        }
        else if(currentScrollTop < lastScrollTop){
            if((currentBgNum < 0197) && (currentBgNum > 100)){
                //decrement image number by 1
                var nextBgNum = Number(currentBgNum)-1;
                //update image      
                nextBgNum = String("0" + nextBgNum);
                var nextBg = currentBg.replace(currentBgNum, nextBgNum);
                document.getElementById("pictureAnimation").src = nextBg;
                lastScrollTop = currentScrollTop;
            }
        }
    }

function bgResize(){

    var newWindowWidth = 0, newWindowHeight = 0;
    var emcPictureHeight = 1080, emcPictureWidth = 1920;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        newWindowWidth = window.innerWidth;
        newWindowHeight = window.innerHeight;
    } 
    else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        newWindowWidth = document.documentElement.clientWidth;
        newWindowHeight = document.documentElement.clientHeight;
    }        
    else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        newWindowWidth = document.body.clientWidth;
        newWindowHeight = document.body.clientHeight;
    }

    var scale = Math.max(newWindowWidth/emcPictureWidth, newWindowHeight/emcPictureHeight);
    var width = scale * emcPictureWidth , height = scale * emcPictureHeight;
    var left = (newWindowWidth-width)/2 , top = (newWindowHeight-height)/2;
    var emcView = document.getElementById("emcView"); 
    document.getElementById("emcView").style.width = width + "px";
    emcView.style.height = height + "px";
    emcView.style.position = "fixed";
    emcView.style.left = left + "px";
    emcView.style.zindex = 0;
    emcView.style.top = top + "px";
    //return true;
}
    window.onload=function() {
        mainScript();
    };

</script>
<noscript>
    <h3>This site requres JavaScript</h3>
</noscript>
<title> ELDP Awesomeness </title>
<style>
    #emcView {
width:10px;
}
</style>
</head>

<body cz-shortcut-listen="true">
    <div id ="emcView">
            <image id = "pictureAnimation" src="Sequence_Pictures/Sequence0100.jpg">
        </div>

</body>
</html>

Answer №1

Make sure to adjust the lastScrollPosition by considering the image filename number, here is a suggested approach:

if(currentScrollTop > lastScrollTop){
    if((currentBgNum < 0196) && (currentBgNum > 99)){
        var nextBgNum = Number(currentBgNum)+1;

        nextBgNum = String("0" + nextBgNum);
        var nextBg = currentBg.replace(currentBgNum, nextBgNum);
        document.getElementById("pictureAnimation").src = nextBg;
        //lastScrollTop = currentScrollTop;   remove this
    }
}
else if(currentScrollTop < lastScrollTop){
    if((currentBgNum < 0197) && (currentBgNum > 100)){
        //decrement image number by 1
        var nextBgNum = Number(currentBgNum)-1;
        //update image      
        nextBgNum = String("0" + nextBgNum);
        var nextBg = currentBg.replace(currentBgNum, nextBgNum);
        document.getElementById("pictureAnimation").src = nextBg;
        //lastScrollTop = currentScrollTop;   remove this
    }
}

lastScrollTop = currentScrollTop;  // Move it here to ensure it is updated with each scroll event

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

Verify in Jquery whether a table row contains no elements with a specified class before removing any duplicates

I have an HTML table: <div class="1233">hello</div> <table cellpadding="0" cellspasing="0" class="sortable zebra tablesorter tablesorter-default" id="articles-table"> <thead> <tr class="tablesorter-headerRow"> ...

The div is not displaying the conditional styling as expected

I need help with mapping an array of cards wrapped in a div. I want the first, second, second-to-last, and last divs to go on a new line or take up the entire row. My project is in Vue3 and I'm using the PrimeVue component library. <div class=" ...

Choose a specific parameter from a line using the body parser in Node.js

Upon receiving a post message, I am having trouble selecting a value from CSV data. Here is a sample of what I receive: { reader_name: '"xx-xx-xx-xx-xx-xx"', mac_address: '"name"', line_ending: '\n', field_delim: & ...

Automated system is responsible for flagging and disabling comments

We are facing a puzzling issue at the moment. Our comments form allows users to submit their thoughts on news articles, and each submission is immediately accepted and displayed on the same page. Within each comment, there is a link that enables users to ...

failure to properly assign a property during model update in mongoose

My BaseSchema contains logic that should set values for two properties when a new Model is created: schema.pre("save", function (next) { if (!schema.isNew) { this.createDate = new Date(); this.createBy = "kianoush"; } next(); }); If updating, ...

Request to convert jQuery Ajax code into Vanilla JavaScript code

Are there any vanilla JavaScript alternatives available for the code snippet below? function verifyEmail() { var apiUrl = "https://apilayer.net/api/check?access_key=c5118f1f9827f42a5fc4b231932130a8&email=" + document.getElementById('email&apos ...

Are we looking at a declaration of an arrow function? Is this concept even real?

I have been exploring the concept of function expressions versus function declarations with arrow functions. From my understanding, this is an example of an arrow function expression: const fred = greeting = () => { console.log("Hello from arrow ...

Issues with CSS filters affecting the layout of webpage elements

Is there a way to keep a div pinned to the bottom of the viewport while applying a filter to the body in CSS? I tried using position: fixed; bottom: 0px, but it seems to mess up the positioning when a filter is added to the body. body { filter: bright ...

Ways to Retrieve JavaScript Variable inside HTML Tags in a JSP

I am currently facing a requirement where I must assign js variables to html input tag ids. For example: <input type='text' id='(here I need js variable)'/> I am aware that one way to achieve this is by creating the entire elem ...

Do we really need TypeScript project references when transpiling with Babel in an Electron project using Webpack?

Currently, I am in the process of setting up my project configuration and have not encountered any errors so far. However, based on my understanding of the Typescript documentation... It appears that Project references are not essential when using babel-l ...

Utilizing various AngularJS filters with multiple input sources

Looking to enhance my user array filtering process with two input boxes. Here's how the array is structured: $scope.users = [{ id: 1, fname: 'Sophia', lname: 'Smith', email: '<a href="/cdn-cgi/l/email ...

Can someone explain the variance between these two script codes? Are they entirely distinct, or can I utilize just one source?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> It appears that one script is for jQuery and the ...

Move an object in relation to the right boundary of the viewport

I have a div that starts off the screen due to this CSS code: transform: translateX(100%); Now, I am looking to bring this div back into view by a specific distance from the right side. Although I have tried using transform: translateX(-450px), it seems ...

Designing a webpage layout with DIV elements that span across multiple rows

I am attempting to create a layout that features two columns, with the right column spanning two rows. I am looking to accomplish this using only DIV tags: +-----------+-----------+ + + + + + + +-----------+ ...

Is there a way to prevent a user who is already logged in from accessing their account on a different browser or tab

My current stack consists of reactjs, nodejs, and redux for user authentication. I am utilizing aws cognito to handle the user authentication process. The main functionality of my app is uploading files from users to an s3 bucket. One of my goals is to p ...

What techniques can be used to ensure that an ASMX web service sends JSON data to the client in response to an HTTP GET

Trying to integrate the official jQuery autocomplete plugin with an ASMX web service in an ASP.NET 3.5 Web Forms application has been challenging. The autocomplete plugin requires HTTP GET calls with specific query string parameters, but I'm strugglin ...

Display PDF on a separate tab when button is clicked in HTML

Is there a way to open a PDF in a new tab or window when a button is clicked? I've tried using onclick="window.location.href" but it always opens the PDF in the same page. Here's my code: <input type="button" value="Report" onclick="location ...

ReactJS bug: Array rendering problem affected by recent changes

Why does ReactJS remove the first element instead of the middle element when using array.splice to remove an element from an array? This is my code. I am using Redux as well. const reducerNotesAndLogin = (state = initialState, action) => { var tableNo ...

Ways to identify when exclusively visible images are fully downloaded and displayed on a webpage

I have successfully implemented image lazy loading functionality with the following code. Now, I want to ensure that only the visible images download completely and render on the page. How can I achieve this? Check out my code below: $(document).ready(fu ...

Obtain element by selecting a specific class using Javascript

<select class="tmcp-field tillagg-width tm-epo-field tmcp-select" name="tmcp_select_30" data-price="" data-rules="" data-original-rules="" id="tmcp_select_ ...