Timing issue with the animation callback

I have been experimenting with creating a bounce effect on my custom scroller by utilizing the translate3d method for scrolling. I managed to successfully implement it, but now I am facing an issue where if you continuously scroll out of bounds (try double scrolling and keep going until it gets stuck), the content remains out of bounds until you scroll back in the opposite direction.

Here is an example: https://i.sstatic.net/BPZGk.jpg. You can also find the code on this JSFiddle link: JSFiddle.

My Question Is:

How can I create a scrolling bounce effect using JavaScript and CSS?

The following sections are optional to read.

Possible Reason It's Not Working Properly:

I suspect that one reason for this behavior could be related to an animation callback event. If the animation does not occur, meaning the transform value does not change, then the animation callback will not be triggered.

When the content has scrolled all the way to the extreme top or bottom, and you attempt to scroll again before the animation completes (thus the transform value remaining unchanged), the animation callback will not execute and as a result, the content won't bounce back within bounds.

Methods I Have Tried So Far:

One approach I experimented with involved checking if the scroll position changed, and only calling the animation callback function if there was a change detected. However, this method did not yield the desired outcome. Scrolling rapidly out of bounds resulted in a stuttering effect, preventing the content from fully reaching the outer limits before bouncing back. Here is a visual representation: https://i.sstatic.net/noIOE.jpg. Link to the corresponding JSFiddle: JSFiddle.

Another strategy I attempted was adjusting the transform value by 0.1 whenever no change in scroll position was detected, thereby ensuring the animation callback would still be invoked. However, this caused a delay in bouncing back when scrolling out of bounds. To address this delay, I reduced the animation duration for cases where scrolling remained consistent, but encountered another issue - a delayed bounce back after excessive consecutive scrolling out of bounds. You can view this scenario in action on this JSFiddle link: JSFiddle.

console.clear();
// More JavaScript code snippets available here...
#outerWrapper {
  height: 400px;
  overflow: hidden;
  display: flex;
  background-color: black;
}
/* More CSS styles here... */
<div id="outerWrapper">
  <div id="innerWrapper">
    <div id="content">
      // Content goes here
    </div>
  </div>
  <div id="scrollbar">
    <div id="scrollbar_thumb"></div>
  </div>
</div>

Answer №1

For a slight variation between each wheel event to trigger transition, the z component can be utilized effectively. Check out this example

var i = 0;
// onmousewheel
.. el.style.transform = `translate3d(0, 40px, ${i^=1}px)` 

// ontransitionend
.. el.style.transform = `translate3d(0, 0, -1px)`

If the previous method seems too complex, an alternative is to perform a costly query to determine the current translation y value and compare it with the bounceAmount (e.g. 40 in this case). If they are nearly identical (difference smaller than Number.EPSILON), then directly call bounceBack().

var m = getComputedStyle(el).transform.match(/,\s*([^,]*?)\s*\)/)
m ? m[1] : 0 // current translation y

Update:

To instantly bounce back content when required, simply disable the onwheel function during motion initiation and re-enable it after the entire motion has finished. This eliminates the need for the z component trick. View the revised implementation in this demo

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

Instructions for downloading a .zip file sent through a HTTP response (using an axios PUT request)

When the API responds, it should contain a data property with the .zip file I need. However, the format is unfamiliar to me. The format: I attempted to use .blob() as suggested in similar questions on Stackoverflow, but it didn't work for me. The d ...

Tips for streamlining the filter function using replace and split:

Currently, I am utilizing a filter function alongside replace() and split(). Here is the code snippet: jQuery('table .abc').filter((i, el) => jQuery(el).text(jQuery(el).text().replace('a', 'b').split(' ')[0] + &ap ...

Animating elements on a webpage can be achieved by using both

Is there a way to create an animation that moves objects based on button clicks? For example, when the "Monday" button is pressed, the object with the correct color will move down. If any other button like "Tuesday" is clicked, the previous object will mov ...

Populate HTML form with return values using jQuery AJAX

I am struggling with retrieving values from jQuery/AJAX and displaying them in an HTML form within the index.php file. This is what my index.php looks like: <script type="text/javascript"> $(document).ready(function () { $('#display'). ...

Having a parameter that contains the characters '&' and '&' can potentially disrupt an AJAX call

Even though there is a similar question here: Parameter with '&' breaking $.ajax request, the solutions provided do not apply to my specific issue. This is because both the question and answers involve jQuery, which I am not familiar with. I ...

Gaining entry to a JSON object within an array

I've completed various courses on JSON and put in a lot of effort to troubleshoot this bug. However, it seems that my question is too specific and I require a practical example. JSON { "date": "2017-10-15", "league": "NHL", "odds": "spreads", ...

Using a timer to make Ajax calls twice on a single webpage

Can multiple ajax calls be made simultaneously on the same page to different receiving div tags? I am struggling to find a solution to this issue. I have a total of 3 pages: a home page, and two PHP pages named status and alert which echo the results. Wi ...

Having an issue with button onClick functionality not working in Javascript

Simple enough. I am struggling to get my button to generate the necessary input upon clicking. The fields should populate where the "household" class is located. I am limited to editing only Javascript and not HTML. Any suggestions? HTML: <ol ...

Ways to verify if a specific email and name are already present in MongoDB

I need to check if a selected user's email and name already exist in my MongoDB database. I want to ensure that both the email and name are unique, without any duplicates of these values. Although I have functional code for this task, I am curious if ...

Leverage data retrieved from a JSON response to dynamically populate variables on a webpage through an AJAX API

After making an AJAX call to my API and receiving JSON data, I am looking to dynamically update my webpage using specific values from the JSON response. <div class="Name"></div> <div class="Role"></div> <div class="Location"> ...

JavaScript must be able to detect when the checkbox value is reversed, which is dependent on the user-entered data

Hey there, I come across a situation where users are selecting a checkbox to insert or update a row of data in a MySQL database through SparkJava/ Java. The functionality is working fine except for a minor glitch. The issue arises when the checkbox behav ...

Issues with loading NextJS videos can occur when accessing a page through a link, as the videos may fail to load without

Issue Greetings. The problem arises when attempting to load muse.ai videos on-page, specifically when accessing the page with a video embedded through a NextJS link. To showcase this issue, I have provided a minimal reproducible example on StackBlitz her ...

Boss declares, "Display the iFrame with no borders visible."

Good day to everyone, I am currently dealing with an issue on the page: It seems to be working perfectly in all of my browsers except for Internet Explorer. Since I don't have IE, I'm having trouble troubleshooting this. My boss mentioned somet ...

How can you position an element at the bottom of a div using CSS?

Could you please assist me in aligning an element to the bottom of a div using CSS? Below is a screenshot of my webpage for reference: http://prntscr.com/5ivlm8 (I have indicated with an arrow where I want the element to be) Here is the code snippet of m ...

Strange behavior occurs when a DOCTYPE is specified in XSLT and javascript interactions

Within our XLST, we utilize "vanilla" JavaScript to manipulate certain div elements within our reports. One particular div sits in the center of the screen and overlaps all other content. The code snippet below is used to position this div when the page lo ...

Steps for integrating a Facebook Messenger chatbot with a MongoDB database in order to submit requests and retrieve responses through conversations with the bot

I am currently working on integrating my Facebook Messenger chatbot with a MongoDB database. The chatbot I have created is a simple questionnaire chatbot that takes text inputs and displays buttons with options. When a user clicks on a button, it should ...

Creating dynamic TextBox fields in JSP based on the selected option from a dropdown menu fetched from the database

Hello, I need some assistance in creating dependent Textboxes based on Dropdown values fetched from a database using Jsp. The code provided below is working fine for one Textbox, but I am unsure how to extend it for multiple dependent Textboxes. Any help w ...

Break up every word into its own separate <span>

I am currently facing an issue with displaying an array of strings in HTML using spans. These spans are wrapped inside a contenteditable div. The problem arises when a user tries to add new words, as the browser tends to add them to the nearest existing sp ...

Efficient Techniques for Concealing and Revealing Navigation Menus using HTML, CSS, and JavaScript

I need help making the menu icon toggle the navigate menu between showing and hiding when clicked on the top right corner of the screen. For better understanding, here is an accompanying image: https://i.stack.imgur.com/oy6d9.png However, the current co ...

I am currently experiencing some challenges with using jquery ajax post in conjunction with PHP

I am facing an issue with jQuery AJAX post and PHP. My attempt is to send data using .serialize() along with additional data. However, in PHP, I can only receive the data from .serialize() but not the additional data. In my jQuery Ajax code, f ...