What could be causing my onscroll function to cut off before reaching the end of the element?

Struggling with a function I created to slide a div horizontally into view in the center of a vertically scrolling page. It seems to work well under normal conditions, but when the page is scrolled quickly, it sometimes fails to complete the horizontal movement. It's particularly troublesome when it stops short of reaching the left-most edge of the browser. Any ideas on how to resolve this issue?

Interested in troubleshooting? Check out the codepen link: https://codepen.io/ThatWerewolfTho/pen/xxRZERv

HTML


      <div class="wrapper">
        <section id="section1" class="full-screen">
          <div class="container">
            <div class="container-inner">
              <h1>This is a very complicated case Maude. You know, a lotta ins, a lotta outs, lotta what-have-yous. There's a lot of strands to keep in my head, man.</h1>
            </div>
          </div>
        </section>
      
        <section id="section2" class="full-screen side-scroll">
          <div class="container">
            <div class="container-inner">
              <h1>I am not Mr. Lebowski. You're Mr. Lebowski. I’m the Dude! So that’s what you call me. That or, uh His Dudeness, or uh Duder, or El Duderino, if you’re not into the whole brevity thing.</h1>
            </div>
          </div>
        </section>
      
        <section id="section3" class="full-screen">
          <div class="container">
            <div class="container-inner">
              <h1>Saturday, Donny, is Shabbos, the Jewish day of rest. That means I don't work. I don't drive a car. I don't fuckin' ride in a car. I don't handle money. I don't turn on the oven and I sure as shit don't fuckin' roll!</h1>
            </div>
           <div>
        </section>
      </div>
    

CSS


    body {
      box-sizing: border-box;
      color: #fff;
      margin: 0;
    }
    
    .full-screen {
      text-align: center;
    }
    
    .container {
      height: 100vh;
      position: relative;
      width: 100vw;
    }
    
    .container-inner {
      left: 0;
      margin: 0;
      padding:0 2rem;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
    
    #section1 {
      position: fixed;
    }
    
    #section1 .container {
      background-color: #bd1a54;
    }
    
    #section2 .container {
      background-color: #c9bfec;
      left: 100%;
      position: fixed;
      top: 0;
      translate: transformY(-50%);
    }
    
    #section3 .container {
      background-color: #35b761;
    }
  

JS


    const sideScroll = () => {
      const docWidth = document.body.clientWidth
      const target = document.getElementById('section2')
      const targetChild = target.querySelector('.container')
      
      // Set the horizontal div height to give the illusion of stasis
      target.style.height = `${docWidth}px`
      targetChild.style.left = `${docWidth}px`
      
      const scrollThis = () => {
        // Find the top of the horizontal scrolling div container
        let targetRect = target.getBoundingClientRect()
    
        // Compare it against the bottom of the window
        // If it's in the viewport, tell the horizontal div that it's cool to come in
        const windowBottom = window.innerHeight
      
        let output = false
        if (targetRect.top < window.innerHeight) {
          output = true
        }
    
        return output
      }
      
      window.onscroll = scrollThis
    
      const setHorizontalPosition = () => {
        const targetRect = target.getBoundingClientRect()
        const howMuchScrolled = targetRect.height - targetRect.bottom
        const percentageScrolled = (howMuchScrolled / (targetRect.height - window.innerHeight)) * 100
    
        if (scrollThis() === true && percentageScrolled <= 100) {      
          targetChild.style.left = `${100 - percentageScrolled}%`
        }
      }
      
      window.onscroll = setHorizontalPosition
    }
    
    window.onload = sideScroll
  

Answer №1

If the scroll exceeds 100%, the current action will not be completed completely. To address this issue, include an additional condition to ensure that when percentageScrolled is greater than or equal to 100, the action is still executed.

    else if (scrollThis() === true && percentageScrolled >= 100) {      
      targetChild.style.left = 0
    }

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

Styling for the DataTable disappears upon loading jQuery

my PHP file named "zero3data.php" <?php printf('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">'); printf('<thead>'); printf('<tr>'); ...

Restricting the number of mat-chips in Angular and preventing the input from being disabled

Here is my recreation of a small portion of my project on StackBlitz. I am encountering 4 issues in this snippet: I aim to restrict the user to only one mat-chip. I attempted using [disabled]="selectedOption >=1", but I do not want to disable ...

What steps are involved in integrating QuickBlox on your website?

I am completely new to web development and have a question about integrating QuickBlox into my website using JavaScript. I have included the necessary JavaScript files in my website and set up the QuickBlox admin application, but I'm not sure how to p ...

Exploring the art of div transitions and animations using React and Tailwind CSS

I successfully implemented the sidebar to appear upon clicking the hamburger icon with a transition. However, I am now facing the challenge of triggering the transition when the close button is clicked instead. I have attempted using conditional operations ...

Adjust webpage display with JavaScript

Utilizing the mobile-first approach of Zurb Foundation, I successfully created a responsive design. However, my client now requires a direct link labeled "View desktop version" in the footer for when the website is accessed on mobile devices or tablets. T ...

Leverage Angular's constant feature in scenarios that extend beyond the

Even though it may not be recommended, I find it fascinating to use Angular services outside of the angular framework. One example is having .constant('APIprefix','/api') I am curious about how to access the value of APIprefix outside ...

What's the importance of including (req, res, next) in the bodyParser function within Express?

My original use of bodyParser looked like this: app.use(bodyParser.json()); However, I now have a need to conditionally use bodyParser: app.use((req, res, next) => { if (req.originalUrl === '/hooks') { next(); } else { ...

Submitting data to an external PHP file using the JavaScript function $.post

Having issues with the PHP page function ajaxFunction(){ var ajaxRequest; try{ ajaxRequest = new XMLHttpRequest(); } catch (e){ try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequ ...

Adding AngularJS to Syncfusion grid or making the rows clickable and running AngularJS functions can be achieved by following these steps

I'm currently incorporating angularJs and Syncfusion to display data in a table using the Syncfusion grid (). However, I'm encountering difficulties in utilizing angularjs functions within this grid: <div class="table-responsive grid-tog ...

Extracting Query Parameters from a Successful Ajax Call in Javascript

How can I extract data from the success response? Take a look at my code snippet: $.ajax({ async: 'true', url: 'https://exampleapi.com/product', type: 'GET', data: {page: idQuery}, success:(response => { v ...

Discovering browser back button press event utilizing Angular

Can we identify when a user has navigated to a page using the browser's history back button? I am looking for a solution in angular.js without relying on angular routing. Additionally, it should also detect if a user returns to a form after submitting ...

What is the best way to display an HTML page in the bottom right corner instead of within a div?

I am trying to display the content of an HTML page in the bottom right corner of another page using my JavaScript script. However, I do not want to insert a div into the page and then load the content inside it. Instead, I am looking for an alternative way ...

What kind of data type should the value property of Material UI TimePicker accept?

While reviewing the documentation, I noticed that it mentions any, but there is no clear indication of what specific data types are supported. The value sent to the onChange function appears to be an object rather than a Date object, and in the TypeScrip ...

Is it possible to incorporate HTML content into the metadata within the head section of a Nuxt application?

Received HTML content from the backend that needs to be incorporated into the meta tag of the HTML head using nuxt. Encountered an error when attempting to display the received content View Error Outlined below is the code implementation: Snippet of Code ...

Tips for managing the ever-evolving language state in expressJS

I am currently working on a project utilizing nodeJs, handlebars, and the expressJs framework. I have implemented a language change functionality using the i18n-express module. This module adds a query string at the end of the URL when changing languages. ...

Guide to changing the border color in a Material-UI TextField component styled with an outline design

To complete the task, utilize the Material UI outlined input field (TextField component from "@material-ui/core": "^4.12.2",) and apply a custom blue color style to it. Here is the outcome of my work: https://i.sstatic.net/lw1vC.png C ...

Unable to alter the vertex color in three.js PointCloud

I'm currently facing an issue with changing the color of a vertex on a mouse click using three.js and Angular. After doing some research, I believe that setting up vertex colors is the way to go. My approach involves setting up vertex colors and then ...

Can Firebase lists be reversed?

I have searched extensively on SO for an answer to this question, but I haven't found a solution yet. Therefore, please do not mark this as a duplicate. Currently, I am working with AngularFire in Angular 2 and Typescript. I am using FirebaseListObse ...

The code encountered an error because it was unable to access the property 'style' of an undefined element on line 13 of the script

Why is it not recognizing styles and showing an error? All paths seem correct, styles and scripts are connected, but it's either not reading them at all (styles) or displaying an error. Here is the html, javascript, css code. How can this error be fix ...

I'm wondering if you have any insights on how to retrieve objects using Mono WebAssembly

I am looking to send a c# object back via mono-wasm, but when I attempt to do so, the returned object appears in my JavaScript file here. The C# code can be found in [image2]: C# code My JavaScript code can be found here: JS code Everything seems to wor ...