Is there a problem with scrolling when using .animate() and .prop() functions?

When scrolling one of two divs with the same class, I want the other div's scroll to reset to 0 with a smooth animation. While achieving this using .prop() is easy, using .animate() only works once and then stops. Any suggestions on how to make the scroll animation work continuously?

Please note: The divs will have the same class and there may be more than two divs in total.

Below is the code snippet I've been working on, any guidance on where I might be going wrong would be appreciated.

$(document).ready(function() {

  $('.swipe_div').scroll(function() {


    // $(this).siblings(".swipe_div").animate({scrollLeft: 0},100);
    $(this).siblings(".swipe_div").prop({
      scrollLeft: 0
    });

  });
});
body,
html {
  width: 100%;
  height: 100%;
  background-color: green;
  padding: 0;
  margin: 0;
}

.swipe_div {
  display: block;
  float: left;
  width: 100%;
  height: 100px;
  overflow-x: scroll;
  background-color: white;
}

.content,
.operation,
.swipe_container {
  display: block;
  float: left;
  height: 100%;
}

.swipe_container {
  width: 150%;
}

.content {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex-direction: row;
  text-align: right;
  font-size: 30pt;
  width: 67%;
  background-color: grey;
}

.operation {
  width: 33%;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="swipe_div">
  <div class="swipe_container">
    <div class="content">
      &#x3e;
    </div>
    <div class="operation">

    </div>
  </div>

</div>

<div class="swipe_div">
  <div class="swipe_container">
    <div class="content">
      &#x3e;
    </div>
    <div class="operation">

    </div>
  </div>

</div>

Answer №1

When animating the scrollLeft property, it triggers the scroll() function on a sibling element, causing conflicts with the active scrolling on the current div. To resolve this issue, you need to track when scrolling starts and use throttle() to limit subsequent calls to scroll() until scrolling is completed.

The option trailing:true allows for one final call after a set interval (250 in this case) without triggering further scrolling by setting the scrolling marker back to false:

$(document).ready(function() {
  var scrolling;
  $('.swipe_div').scroll(_.throttle(function() {
    if (!scrolling) {
      scrolling = true;
      $(this).siblings(".swipe_div").animate({scrollLeft: 0},150);
    } else {
      scrolling = false;
    }
  }, 250, {leading:true,trailing:true}));
});
body,
html {
  width: 100%;
  height: 100%;
  background-color: green;
  padding: 0;
  margin: 0;
}

.swipe_div {
  display: block;
  float: left;
  width: 100%;
  height: 100px;
  overflow-x: scroll;
  background-color: white;
}

.content,
.operation,
.swipe_container {
  display: block;
  float: left;
  height: 100%;
}

.swipe_container {
  width: 150%;
}

.content {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex-direction: row;
  text-align: right;
  font-size: 30pt;
  width: 67%;
  background-color: grey;
}

.operation {
  width: 33%;
  background-color: red;
}
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="swipe_div">
  <div class="swipe_container">
    <div class="content">
      &#x3e;
    </div>
    <div class="operation">

    </div>
  </div>

</div>

<div class="swipe_div">
  <div class="swipe_container">
    <div class="content">
      &#x3e;
    </div>
    <div class="operation">

    </div>
  </div>

</div>

I tested the implementation briefly and encountered a small glitch/limitation: the throttle interval must be shorter than the animation duration. If not, the animation may exceed the throttle interval and trigger the closing animation of the original scrolled element.

However, in web development, challenges can always be overcome. In cases where the animation duration exceeds the throttle interval, you can mark the initial element with a specific class to exclude it from animations. The class will be removed via a timeout upon completion of the animation, which is equal to the throttle interval:

$(document).ready(function() {
  var scrolling;
  $('.swipe_div').scroll(_.throttle(function() {
    if (!scrolling) {
      scrolling = true;
      $(this).addClass('original');
      $(this).siblings(".swipe_div:not(.original)").animate(
        {scrollLeft:0},
        250,
        function(){
          setTimeout(function() {
            $('.swipe_div').removeClass('original')
          }, 150)
        }
      );
    } else {
      scrolling = false;
    }
  }, 150, {leading:true,trailing:true}));
});

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

Exploring the height and overflow properties of nested div elements

Imagine a scenario where you have a fixed-size container and need all the elements to fit inside. The issue arises when some elements contain lots of text, causing the overflow to be hidden but still stretching beyond the container's height. How can t ...

Set up Node.js application to allow CORS for designated endpoint(s) exclusively

I am currently facing a dilemma with my Node application and how to handle cross-origin resource sharing. In the past, I have used a PHP proxy to bypass this issue when calling endpoints from JavaScript/AJAX. However, I am now looking to streamline the pro ...

Populate Jquery datatables programmatically

After implementing the Jquery Datatables plugin, I initially had hardcoded content in the table. However, I made some modifications to dynamically populate the table with fetched data. While this change worked fine, I encountered issues with the search f ...

How can I use the draggable and droppable features to add <li> elements to a <ul> list?

I'm encountering a small issue with controlling the placement of my <li> elements when I implement draggable and droppable from JQuery UI. To better explain the problem, I have created a detailed fiddle: JSFiddle Why is it that the .courseBox ...

Implementing a multi-level 'Add More' feature with jQuery

I am trying to create a dynamic "Add more" button feature using jQuery. Although I managed to implement the functionality, unfortunately, it is not successful as there are several bugs and logical issues present. My requirement is to have an "Add more" b ...

How can I efficiently create a suffix using this JavaScript code?

Take note that the code displayed below showcases the array in the console, rather than in the snippet output var names = ["maria", "mary", "marks", "michael"]; function add_suffix(names) { var suffixes = []; for (var i = 0; i < names.length; i+ ...

Two-Tone HTML Button: A Stylish Design featuring Dual Border Colors

Here's the HTML code I've written for a button: <input style="border-width: 624px; border-color: rgb(252, 255, 158);"> However, when I view it, the color on the top left is correct, but there's an unexpected color on the bottom right ...

Uploading files from a local directory to an API using node.js and multipart/form-data

I'm struggling to figure out how to upload a local file to a RESTful API service from my JavaScript application. The file I want to upload is located at "c:/folder/test.png" and I need to upload it to something like "localhost/uploads". I've sear ...

Delving Into the Depths of Scope in jQuery

Essentially, I have a function with the following code snippet: (function ($) { // mouseenter event for each menu item $menuItems.bind('mouseenter', function (e) {}); })(jQuery); My goal is to be able to access $menuItems from this fu ...

Transform strings in a table into integers within a specified scope

My World.json file is quite large and contains extensive data on countries worldwide. I've been utilizing a list to display this data in a table format, with the intention of sorting all values accordingly. However, I have encountered an issue - all m ...

"Encountering a glitch with masterpage.cs in Aspx.net and C#

Currently facing a perplexing issue while developing a website using aspx.net and c#. The following code snippet is on my masterpage: protected void Page_Load(object sender, EventArgs e) { if (HttpContext.Current.Request.Url.AbsolutePath == "/ ...

How can I use an array to dynamically populate an option html tag in react?

I am attempting to populate an option in jsx with values from an array called currencyOptions. Despite using this method, the options are remaining blank. The array is passed down to the component as a prop, set using useState, and the data is fetched from ...

How can we accurately identify if string inputs include HTML tags?

When gathering user input from forms, I need to ensure that fields like "username" or "address" do not contain any markup that could pose a risk in XML (RSS feeds) or (X)HTML (when rendered). So, how can I correctly determine if the input provided does no ...

Ensure that buttons are cropped when extending beyond the border of another DIV

My issue involves a main DIV with buttons contained within it. I am seeking a solution to ensure that the buttons are cut off at the edge of the DIV, similar to the concept illustrated in this image. In the image, the blue represents the body, the light gr ...

Looking for the optimal width ranges for media queries on laptops and cell phones?

Can anyone suggest the optimal width parameters to use in my code for different screen sizes, from tablets and laptops to cellphones, in order to create a responsive design? ...

What occurs when multiple HTML tags are assigned the same string as their ID attribute value?

While browsing a html page, I stumbled upon several tags that I thought had the same id. It turns out they were unique, but it got me thinking - what would happen if multiple tags actually shared the same id? I've always heard that the id attribute o ...

Mastering the Art of Scrolling to a Specific Div with jQuery Animation

I've been searching for a solution on stack overflow, but because I'm not very proficient in jquery, I haven't been successful. My question is, how can I smoothly scroll from the top of the page to a specific div? I've successfully ach ...

The element type provided is not valid: it should be a string (for built-in components) or a class/function. Utilizing SSR with Node.js, React, and React-

Playground: https://codesandbox.io/s/focused-dream-ko68k?file=/server/server.js Issue Error: Encountered an error stating that the element type is invalid. It was expecting a string or a class/function, but received undefined instead. This could be due ...

AngularJS object array function parameter is not defined

Recently, I've been honing my AngularJS1x skills by following tutorials on Lynda and Udemy. One tutorial involved creating a multiple choice quiz. To test my understanding, I decided to modify the code and transform it into a fill-in-the-blank quiz. ...

What is the integration of Google URL format with a PHP application?

When it comes to php websites, URLs are commonly written in the form of page.php?id=123 or rewrite moded page/Id/123 However, when looking at google I observed that URLs look more like google.com/search?q=Wordpress I attempted to structure website links ...