Problem with animated scrolling in Jquery

Currently, I am working on a function that aims to smoothly scroll the web to a specific div each time a user scrolls "into" a container div. You can get a better idea of what I mean by looking at my JSFiddle.

Everything works perfectly when the user scrolls slowly or uses arrow keys. However, if the user performs an abrupt scroll, the animated scrolling becomes jerky and sometimes even jumps in the opposite direction mid-animation.

I'm not entirely sure if this issue is connected to momentum scrolling or the rapid increase in scroll speed when the user spins the scroll wheel very fast. It could also be due to some other reason that hasn't crossed my mind yet.

Below is the basic code needed to replicate the bug (same as in my JSFiddle):

HTML:

<body>
  <div style="background-color:red;" class="autoscroll">
    <p style="line-height:3;color:white;">
    Ipsum Lorem<br><br>Ipsum Lorem<br><br>Ipsum Lorem<br><br>Ipsum Lorem<br><br>Ipsum Lorem
    </p>
  </div>
  <div style="background-color:blue;" class="autoscroll">
    <p style="line-height:3;color:white;">
    // Contents here...
    </p>
  </div>
  <div style="background-color:green;" class="autoscroll">
    <p style="line-height:3;color:white;">
    // Contents here...
    </p>
  </div>
  <div style="background-color:brown;" class="autoscroll">
    <p style="line-height:3;color:white;">
    // Contents here...
    </p>
  </div>
</body>

CSS:

.autoscroll{
  min-height:100%;
}
html, body, p{
  margin:0;
  padding:0;
}

JS:

// JavaScript code snippet here...

In addition to the above, I have two functions called disableScroll and enableScroll. While I did not include them in my JSFiddle, hoping to fix the issue with their help, it seems like the bug persists regardless. I seek advice on whether I should retain or remove these functions.

// Function definitions for disableScroll, enableScroll, etc.

Despite conducting thorough research on this matter, I haven't been able to find a solution. Any assistance would be greatly appreciated. Thank you.

Answer №1

It seems like your code might be a bit complex, but I've made some modifications that could help or give you new ideas.

If you want to see the changes I made, check out my updated fiddle here.

I suggest using the cross-browser jQuery mousewheel plugin available at https://github.com/jquery/jquery-mousewheel. It simplifies your event listener to this:

$(document).on('mousewheel keydown',function(event){ });

I also implemented the isElementInViewport method found here.

To check visibility of div tops and bottoms in the viewport, I added marker elements as-top and as-bottom to the HTML structure like this:

 <div class="autoscroll">
    <div class="as-top"></div>
    <p>Lipsum stuff...</p>
    <div class="as-bottom"></div>
  </div>

That's all for now, hope these updates are helpful!.

Answer №2

Looking at another perspective:

https://jsfiddle.net/92nf4qpj/2/

The code has been completely revamped. It now utilizes timeouts and solely relies on the scroll event, making it compatible with touch screen devices.

Enables quick scrolling and resolves the padding issue in your container by using a single marker

<div class="as-marker"></div>
before each container. No longer requiring the mousewheel plugin.

This could easily be transformed into a jQuery plugin for convenient reuse on multiple scrollable elements.

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

Linking Redux to the highest level of my application is not functioning as expected

I have been attempting to troubleshoot this code for quite some time now, but I am struggling to identify the issue at hand. My main goal is to establish a connection between my top-level application and the redux store. However, every time I try, the stor ...

Customize the appearance of the Vue.js datepicker starting from today's date

I am currently using the vue-datepicker component to display a date input field in my form. I want to set the default date to the current day and disable the selection of past dates. Additionally, I need to change the language of the component but it seems ...

The data retrieved by jQuery AJAX is empty when accessed outside of the success handler

Here is a code snippet to consider: let source = null; fetch('https://example.com/data') .then(response => response.json()) .then(data => { source = data; console.log(source); }); console.log(source) When the fetch request ...

UI-Router: What is the best way to access a page within my project without adding it as a State?

Currently in the process of learning Angular and UI-Router. Initially, I followed the advice of many and chose to utilize UI-Router. In my original setup, the login page was included in all States. However, I decided it would be best to keep it as a separ ...

Leveraging partials on their own

I am currently exploring the possibility of loading a partial in linkedin-dustjs without having to load its parent along with it. For instance, consider this partial (login.dust): {>layout/} {<content} <!-- Login Screen --> {/content} Th ...

Having trouble with your mobile dropdown menu not responding to clicks?

I'm having trouble getting a dropdown menu to work on the mobile version of my website. When I click on the dropdown menu image, it's supposed to appear, but it's not working as expected. JSFiddle: https://jsfiddle.net/xfvjv184/ Included ...

The choice between using "npm install" and "npm install -g" for

New to the world of node, and feeling a bit lost when it comes to all this "install" stuff. Could someone clarify for me, what sets apart install from install -g? If something is installed with install -g, can it be accessed from anywhere, or is it restr ...

Should ng-binding be avoided in CSS selectors as a general rule?

Recently, I stumbled upon this code snippet in our codebase: li.ng-binding span { font-size: 13px; font-family: Arial, Helvetica, sans-serif; font-weight: bold; } The selector above doesn't actually apply to one of the intended 'li& ...

The ajax PUT request encounters an internal server error and does not succeed

handleSurprise(userResponse) { // function to handle user's surprise response var updateURL = "/" + serviceContext + "/service/updateinfo/"; var userRespString = JSON.stringify(userResponse); var parsedUserResponse = JSON.parse(userRespS ...

Exploration of frontend utilization of web API resources

I've come across this issue multiple times. Whenever I modify a resource's result or parameters and search for where it's utilized, I always end up overlooking some hidden part of the application. Do you have any effective techniques to loc ...

Display an AJAX div when the image is hovered over and have it track the movement of

I am seeking assistance with my website project, which involves providing users with download links to movies. However, I am struggling to make the preview_block div(id) appear when the mouse hovers over the movie_block div(id). Additionally, I am having ...

When accessing nested objects in Props in Vue.js, an error may occur if the property of null/undefined

When I make an axios call, I receive an object which I pass to a child component. However, when I attempt to loop through the object in the child component to access a property of another nested object, I encounter an issue where the property is showing as ...

Browser Compatibility with AngularJS

Encountering an issue with AngularJS compatibility - are there any features not supported by Google Chrome? We have developed the AngularUI Calendar and utilized the JSFiddle link below: http://jsfiddle.net/joshkurz/xqjtw/52/ The UI calendar works on Fi ...

AngularJS: Issue with inputMask functionality within an angularJS table

Within my ng-repeat table, I have two date fields. Here is the code snippet: <tr ng-repeat="ol in orderLines"> <td> <input class="audioStartTime" type="text" ng-model="ol.AudioStartTime"/> </td> <td> ...

Efficiently utilizing CSS classes

My dilemma involves styling a textfield in two different locations on my website, each with its own parent element. The second location requires an additional margin-top that the first does not. What is a clever way to adjust the original margin-top withou ...

Creating a RESTful API

To begin with, I am a newcomer to web frameworks and we are currently using Meteor. In our database, we have a collection of Students: Students = new Mongo.Collection('students'); At the moment, we have defined a Rest API as follows: // Maps t ...

Show the current time of a track using VueJS

Is there a way to have the time continuously update itself without needing to click on anything? When I press play, I want the seconds to automatically start updating from 0:00 until the end of the audio track. Currently, the time only updates when clicked ...

What could be causing such a significant variance in performance for a wrapped JavaScript function?

Here is a code snippet that I have been experimenting with: function Run () { var n = 2*1e7; var inside = 0; while (n--) { if (Math.pow(Math.random(), 2) + Math.pow(Math.random(), 2) < 1) inside++; } return inside; } var s ...

The <h:outputStylesheet> tag fails to display any content on the HTML page

I am having trouble getting my CSS sheet to load while using JSF2 and PrimeFaces. The CSS file is located at WebContent/resources/css/style.css Here is the xhtml code: <h:head></h:head> <h:body> <h:outputStylesheet name="css/styles. ...

Trouble initializing Google Maps in an Angular directive

I'm currently working on integrating the Google Maps API into an Angular website, but I'm encountering initialization issues. Within my HTML page, I'm utilizing bootstrap nav nav-tabs and switching between tabs using an Angular controller. ...