The clash between CSS's 'snap-scroll' and jQuery's '.animate scrollLeft' functionality

My HTML and CSS slider utilizes the scroll-snap feature for manual scrolling along with jQuery buttons for automated scrolling. However, I have encountered an issue where using scroll-snap-type: x mandatory; causes severe lag in the jQuery scrollLeft animation or makes the animation disappear altogether. What could be causing this lag? Is there a potential solution using only jQuery?

Removing the CSS scroll-snap resolves the problem, but it is essential to maintain the slider's style.

HTML

<div class="container">
  <div class="box"></div>
  <div class="box"></div> 
  <div class="box"></div>
</div>
<button id="left">&larr;</button>
<button id="right">&rarr;</button>

CSS

.container {
  max-width: 300px;
  display: flex;
  scroll-snap-type: x mandatory;
  overflow-x: auto;
}
.box {
  min-width: 100%;
  min-height: 250px;
  scroll-snap-align: center;
  scroll-snap-stop: normal;
}
.box:nth-child(1) {background: #f55;}
.box:nth-child(2) {background: #5f5;}
.box:nth-child(3) {background: #5ff;}

jQuery

$("#right, #left").click(function() {
  var dir = this.id=="right" ? '+=' : '-=' ;
  $(".container").stop().animate({scrollLeft: dir+'300'}, 300);
});

Feel free to explore a live example at: https://codepen.io/tystrong/pen/rboLYz

Answer №1

To resolve the issue at hand, I made a simple adjustment by deactivating the `scroll-snap-type` property while the scrolling animation is in progress. Once the animation is complete and the `animate()` function callback is triggered, I re-enable the property.

Below is the revised version of my code snippet:

$arrows.on("click", event => {
  $track.css("scroll-snap-type", "none");

  $track.stop().animate(
    { scrollLeft: left },
    500,
    () => $track.css("scroll-snap-type", "x mandatory")
  );
});

Answer №2

Looking for a smooth scrolling solution that doesn't rely on jQuery animate? The polyfill for smooth scroll behavior might be just what you need to tackle the side scrolling & snapping issue. Check out how you can implement it in your code:

$('#right, #left').click(function() {
  $('.container')[0].scrollBy({
    top      : 0,
    left     : this.id == 'right' ? 300 : -300,
    behavior : 'smooth'
  });
});

One thing to note: while you can't adjust the scroll speed, testing has shown that the smoothness is consistent across desktop Chrome (76.0.3809.132) and mobile Safari (iOS 13.0).

Answer №3

To achieve smooth scrolling with GPU acceleration, you can utilize JavaScript's scrollIntoView method on the desired element within your scroller container. By utilizing this method, the native scroll-snap behavior and animations will be implemented for a seamless and natural scrolling experience.

For a scenario like yours, you could implement the following code:

var boxes = $(".box", ".container");
var target_id = 2; //adjust this dynamically based on current active id and desired scroll location

boxes.eq(target_id)[0].scrollIntoView({
    behavior: 'smooth',
    block: 'start',
    inline: 'start'
});

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

Moving from one page to another

I am attempting to create a transition effect between sections within a single-page application. All the sections are contained on the same page, with only one section displayed at a time while the rest are set to display none. When a specific event is tri ...

Performance issues with jquery addClass and removeClass functions observed in Internet Explorer 11

I am currently working on an application that monitors nodes within a cluster, and I have created a visual state example to demonstrate this. Each small box in the grid represents a node, and when hovering over a node, the rest of the nodes in that particu ...

Having trouble triggering a modal on dropdown selection in Laravel blade?

I have a Laravel application where I need to implement a dropdown menu with three options inside a form. The options are loaded dynamically from the database through my controller. {{ Form::select('roles', $roles , $userRole,array('class&ap ...

Maximizing Bootstrap card size in Angular4: A step-by-step guide

How can I make Bootstrap cards resizable on top of other elements when clicked on an icon to make it full screen and overlay on other cards? detail.component.html <div class="card card-outline-info" > <div class="card-header bg-info"><h5 ...

The href attributes are not being retrieving correctly

I'm currently working on extracting the URLs for each restaurant listed on this page and have developed a Python script for this purpose: import time from selenium import webdriver from selenium.webdriver.common.keys import Keys browser = webdriver ...

jquery target descendants with specific names

In the provided HTML code snippet, there is a main div with the class name of cxfeeditem feeditem, and it contains multiple child elements with similar class names and structure. My query pertains to extracting values from specific children within all the ...

How can one generate an array containing all attributes found in the HTML of a website?

I have a project idea where I want to be able to input a hyperlink address and then get a list of attribute contents as the output. For instance, if I input a Netflix genre hyperlink for Adventure Movies, I'd like to receive a list with all the movie ...

What is the best way to adjust the background color of Material UI's theme based on different screen sizes?

Having trouble replacing hard-coded CSS breakpoints with Material UI theme settings. @media screen and (min-width: 0px) and (max-width: 400px) { body { background-color: red; } } @media screen and (min-width: 401px) and (max-width: 599px) { body { ...

Filter Products with Magento Layered Navigation - Checkbox Options

Is there a method to transform the layered navigation into checkboxes similar to Asos? I have noticed that there are modules available for purchase claiming to offer this functionality. I may consider using one of those, but I wanted to explore any other ...

Verification of date in Bootstrap datepicker

Whenever I manually input a date into the field and then click outside of it, the date value becomes empty if the format is incorrect. I've been attempting to simulate an "enter" event when clicking outside of the input field so that the datepicker c ...

Obtain span value using a CSS selector in Python

I need help extracting the value of a span using a CSS selector soup = BeautifulSoup("<body><main><div class='rentalprice'><span>3.000</span></div></main></body>") pagecontent = soup.find( ...

Accessing the Angular scope and making modifications using Chrome browser

I need to access the $scope value in order to update its data values via a chrome extension. I have attempted to obtain the $scope using the code below: var $scope = angular.element(document.getElementById('name')).scope() While this code wor ...

Steps to connect my CSS with my HTML in a website hosted on GitHub

I am experiencing an issue with my website hosted on Github pages. It seems to be unable to read the CSS file that I have linked to it. Here is a snippet of my HTML code: <!DOCTYPE html> <link rel="stylesheet" type="text/css" href="https://githu ...

Managing asynchronous requests with CodeIgniter

In my approach to handling success and error messages, I have been using json encoded arrays as responses. However, it recently occurred to me that this may not be the most appropriate way to manage notifications. Here's an example of how I handle th ...

What is the easiest way to obtain the rowindex in jQuery datatables for a specified row number?

Let's say I want to retrieve the data from row number 2 in a datatable. Without actually selecting or clicking on the row, my goal is to extract the information from the second row of the table. ...

js/jquery issue with IE: Scrolling to the bottom of a div upon page load

I have encountered an issue with my code on Internet Explorer. It works perfectly on Firefox, but when the content of the div is too high in IE, it fails to scroll to the bottom. Clicking a button to scroll to the bottom works fine, but the problem arise ...

Use ASP.NET MVC to pass data from an action to an AJAX call and utilize it in the success function

I have a custom ResultOfOperation class that I use to retrieve details about an activity: public class ResultOfOperation { public string Message1 { get; set; } public string Message2 { get; set; } public string Message3 { get; ...

Ways to create a back-and-forth transition across a sequence

Is it possible to create an animation that changes the width of an element once, then reverts back after a pause? I want this transition to occur over a three-second interval followed by a two-second delay. How can I achieve this? Below is the code I have ...

Is it possible to retrieve all website links from a page in plain text format?

I am looking to extract all URLs from a web page, regardless of whether they are clickable links or not. For instance, the page source could look like this: <html> <title>Random Website I am Crawling</title> <body> Click <a ...

What is the best way to make the children of a parent div focusable without including the grandchildren divs in the focus?

I want to ensure that only the children of the main div are able to receive focus, not the grandchildren. Here is an example: <div class="parent" > <div class="child1" > <!-- should be focused--> <div class="g ...