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

The issue lies in the error code TS2315 which states that the type 'observable' is not a generic

I keep encountering an error message that says 'observable is not generic' while importing files. I am working on implementing CRUD operations in Angular 7, where I have created two components for adding and listing employees. The functions for c ...

Angular displaying a slice of the data array

After following the example mentioned here, and successfully receiving API data, I am facing an issue where only one field from the data array is displayed in the TypeScript component's HTML element. Below is the content of todo.component.ts file im ...

Displaying numerous information panels on Google Maps by extracting data from MySQL

Help needed! I've been struggling with this code for a while now. I can show multiple markers on the map but can't figure out how to display info details in a pop up box when they are clicked. Currently, I'm just trying to make it say "Hey!" ...

Script causing issue with webservice communication

My webservice seems to be malfunctioning. Here is the script that I am using: <script src="Scripts/jquery-1.11.1.min.js"></script> <script> $(document).ready(function () { $('#btn').click(function () { ...

What could be causing the issue with the malfunctioning Ajax pagination?

I attempted to incorporate ajax-loaded pagination into my project. I successfully followed a tutorial for implementing it in a blank project, but when trying to apply it to my current project, I encountered issues. Although I can navigate through the pagin ...

What could be causing my GET route to return an empty array?

I've been attempting to retrieve an event by its id, but for some reason, I'm receiving an empty array as a result in Postman. Below is the code snippet of my route: import { events } from '../../../db.json'; const handler = async (re ...

Is it possible to resize an image while also adjusting the size of its container using CSS?

I have a block of content with an image sandwiched between paragraphs. <p class="bodytext">aslkjfsdlkfj f ldflskl</p> <p class="image"><img src=1.png/></p> <p class="bodytext">aslkjfsdlkfj f ldfl ...

What is the impact of Javascript variable scope in the context of "for...in..." loops?

Imagine you have a code snippet like this: dict = {"key":"elem"} for (var elem in dict){ someFunction(function(){ anotherFunction(dict[elem]); }) } Question: Is elem still considered as the temporary variable created in the for...in... s ...

Implementing a keypress function that can handle duplicate names

HTML <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="total" type="text" value="0" disabled="disabled"/> Javascript $('[name="pm"]' ...

Creating an Angular application within the success callback of a jQuery Ajax request

Using a jQuery ajax request, the HTML of one of several independent angular apps is loaded and injected into the DOM. Here is a simplified version of the code: $.ajax({ 'url': 'url-to-random-angular-app.html', 'success': ...

Automating the linking of tsd definitions with bower and npm: A step-by-step guide

Currently, I am in the process of transitioning an existing project to TypeScript which includes numerous bower and npm dependencies (bower.json and package.json). As mentioned on the tsd github page, TSD facilitates the discovery and linking of defini ...

Avoiding the backslash in JavaScript

<script type="text/javascript"> console.log(#Fileurl#); jQuery.ajax({ url: "http://xyz:8800/aaa/bbb/ccc", type:'POST', dataType: 'JSON', data:{"file":"#Fileurl#"}, success: function ...

Disable the default form input reset button generated by Internet Explorer 10

Just have one field form for search input. Below is the HTML code: <form class = "search-form hide-on-mobile"> <input class = "global" type = "text" placeholder = "Who are you looking for ?"> <but ...

Encountering NaN while trying to retrieve the duration in JavaScript

I'm having an issue retrieving the duration of an mp4 video file when the HTML document loads. Here's my code: (function ($, root, undefined) { $(function () { 'use strict'; $(document).ready(function() { ...

The React-Chartjs chart is displaying without any color rendering

I attempted to create a radar chart using react-chartjs library, but I am facing an issue where the colors are not appearing when it renders. https://i.stack.imgur.com/tjAsW.png What could be causing this problem? I followed a significant portion of the ...

The attempt to log in using AJAX and PHP was unsuccessful

Why does the output always show a false alert even though the email and password match those in the database? PHP: <?php include 'db.php'; $email = trim($_POST['email']); $password = trim($_POST['password'] ...

Creating smooth animations in JavaScript without relying on external libraries such as jQuery

Is there a way in JavaScript to make a <div> slide in from the right when hovered over, without relying on jQuery or other libraries? I'm looking for a modern browser-friendly solution. const div = document.querySelector('.fro ...

"Is there a way to extract a specific value from an XML file based on another element

<dataset> <study recNO="0" seriesRecCount="1"> <patientID>123456</patientID> <accessionNumber>M120170428105320</accessionNumber> <patientIDID>35</patientIDID> <studyUID>2.25.1439 ...

Authentication in Feathers JS without the need for email addresses

Currently, I am in need of an authentication system for my dApp that operates without using email addresses or storing any user information. What I require is an endpoint where users can submit a seed phrase and password to generate a JWT. The process shou ...

A guide on how to modify a CSS property to set the display to none upon clicking a radio button

Currently, I am attempting to display two input boxes in a table when I select specific radio buttons and hide them if I choose another option. The code I have does work but has a minor issue, function disappear() { document.getElementsByClassName("ta ...