Design a slider that mimics infinite scrolling using CSS

I am attempting to design a CSS slider with infinite scroll functionality, but I want to achieve this without the need to dynamically add or manipulate DOM elements. The goal is for the slider to loop back to the first slide when the last one is reached.

Due to my fixed-width slides, utilizing slick and box slider plugins is not suitable for my project.

.slider-wrap {
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  border: 1px solid red;
}

.slider-wrap .slide {
  display: inline-block;
  width: 200px;
  margin: 5px;
}

.slider-wrap .slide img {
  width: 100%;
}
<div class="slider-wrap">

  <div class="slide">
    <img src="http://via.placeholder.com/350x150">
  </div>
  <div class="slide">
    <img src="http://via.placeholder.com/350x150">
  </div>
  <div class="slide">
    <img src="http://via.placeholder.com/350x150">
  </div>
  <div class="slide">
    <img src="http://via.placeholder.com/350x150">
  </div>
  <div class="slide">
    <img src="http://via.placeholder.com/350x150">
  </div>
  <div class="slide">
    <img src="http://via.placeholder.com/350x150">
  </div>
  <div class="slide">
    <img src="http://via.placeholder.com/350x150">
  </div>

</div>

Answer №1

Consider the following two options:

  • Option 1: Clone the items: This approach is more natural and commonly used on websites to add more content.

  • Option 2: Revert the position of the scroll to make it seem like the slider never ends. Note that this will not affect the size of the scroll bar as the content remains unchanged.


(a) Cloning Method

You can clone the images when the scroll reaches the end of the slider by using the following script:

$(function() {
  $('.slider-wrap').scroll(function() {
    
    const slider = $(this);
          width = slider.innerWidth()
          scrollWidth = slider[0].scrollWidth;
          scrollLeft = slider.scrollLeft();
    
    if(scrollWidth - width == scrollLeft) {
      slider.children().clone().appendTo(slider);
    }
    
  });
});
.slider-wrap {
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  border: 1px solid red;
}

.slider-wrap .slide {
  display: inline-block;
  width: 200px;
  margin: 5px;
}

.slider-wrap .slide img {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider-wrap">
  <!-- Add your slides here -->
</div>


Demo of the Cloning method:

$(function(){$('.slider-wrap').scroll(function(){const slider=$(this);var $width=slider.innerWidth()
var $scrollWidth=slider[0].scrollWidth;var $scrollLeft=slider.scrollLeft();if($scrollWidth-$width==$scrollLeft){slider.children().clone().appendTo(slider)}})})
.slider-wrap{white-space:nowrap;overflow-x:auto;overflow-y:hidden;border:1px solid red}.slider-wrap .slide{display:inline-block;margin:5px}.slider-wrap .slide img{height:120px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="slider-wrap"> <!-- Add your slides here --> </div>


(b) Using ScrollLeft Hack

An alternative method involves resetting the scroll position back to the first slide container whenever a new slide is added, which can be achieved with the following script:

let firstPos = undefined;

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

  const slider = $(this);
        width = slider.innerWidth()
        scrollWidth = slider[0].scrollWidth;
        scrollLeft = slider.scrollLeft();
        isEndOfSlider = (scrollWidth - width) == scrollLeft;
        numberOfWraps = slider.children().length;


  if(isEndOfSlider) {    
    
    if(numberOfWraps == 1) {

      firstPos = scrollLeft;
      slider.children().first().clone().appendTo(slider);

    } else {

      slider.scrollLeft(firstPos);

    }      

  }


});
.slider {
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  border: 1px solid red;
}

.slider-wrap {
  display: inline-block;
}

.slider-wrap .slide {
  display: inline-block;
  width: 200px;
  margin: 5px;
}

.slider-wrap .slide img {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider">
  <div class="slider-wrap">
    <!-- Add your slides here -->
  </div>
</div>


Demo of the ScrollLeft hack:

let firstPos=undefined;$('.slider').scroll(function(){const slider=$(this);width=slider.innerWidth()
scrollWidth=slider[0].scrollWidth;scrollLeft=slider.scrollLeft();isEndOfSlider=(scrollWidth-width)==scrollLeft;numberOfWraps=slider.children().length;if(isEndOfSlider){if(numberOfWraps==1){firstPos=scrollLeft;slider.children().first().clone().appendTo(slider)}else{slider.scrollLeft(firstPos)}}})
.slider{white-space:nowrap;overflow-x:auto;overflow-y:hidden;border:1px solid red}.slider-wrap{display:inline-block}.slider-wrap .slide{display:inline-block;margin:5px}.slider-wrap .slide img{width:auto;height:120px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="slider"> <div class="slider-wrap"> <!-- Add your slides here --> </div></div>

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

Adding a new HTML element to each ng-repeat iteration in AngularJS

Can you help me find a solution for inserting a <p> tag in the DOM for each item in my ng-repeat loop? Here is the array of objects I am using for the ng-repeat: $scope.items = [ {name: "john", paragraph:"<p>hi, im john</p>"}, {nam ...

Filtering nested objects in JavaScript based on a specific property value

I have a list of objects nested in JavaScript and I need to filter them based on a specific search string and property value. My goal is to extract only the categories with children that are not hidden and contain at least one profile with a name matching ...

Unleashing the power of ::ng-deep to access CSS in an Angular child component

I'm attempting to modify the CSS class of a child component by using ::ng-deep. Despite my efforts with various iterations of the code provided below, I have been unsuccessful in accessing the CSS. The structure of the HTML component is depicted in th ...

Retrieve and dynamically load an entire webpage using AJAX

Although it's typically not recommended, I am interested in displaying the progress of a download on a heavy page to show the user when it's ready. Is there a way for me to track and display the actual progress of the download? Can I monitor how ...

Create an AngularJS task manager that saves your to-do list even when the page is refreshed

Currently, I am developing a straightforward to-do list application using AngularJS within an ASP.NET MVC template. Surprisingly, I have successfully integrated Angular and Bootstrap to achieve the desired functionality. The app allows users to add and re ...

Opacity property in CSS does not have any impact on the child elements

Similar Question: how do I prevent opacity from affecting child elements? Can CSS or jQuery be used to apply transparency or opacity to an element without affecting its children? ...

Executing MySQL queries through JavaScript functions

I need to create a PHP function that I can use in my JavaScript code. The issue I'm facing is that the variables from the beginning of the file are not recognized in the JavaScript block. <!DOCTYPE html> <?php include 'pdo_connect.php&a ...

The Ng-include tag does not provide highlighting for its text

Within an ng-include template, I have a div that is not highlighting when hovered over. Although the cursor changes to a pointer when hovering over the text, attempting to click and drag to highlight it results in nothing happening. This issue is signific ...

Perform an action when a key is held down and when it is released

I am looking to implement a function that needs to be called under certain conditions: It should be triggered every second while a key is being held down (for example, if the key is held down for five seconds, it should fire 5 times every second). If ...

Tips for Sending Information to the Current Page Using JQuery

I am attempting to send the form data back to the same location as the form itself. The code needs to: Trigger the click action for #submit Retrieve data from #email, #selection1, and #selection2 Hide the form #form Show the data in #email, #selection1, ...

What is the best way to transfer data from a clicked table row to another component?

I am currently working on developing an email inbox component for a system where the emails are displayed in a table format. When a user clicks on a specific row, it should lead to another component for further details. Since the information is not rende ...

What is the best way to steer a vehicle in the desired direction by utilizing the arrow keys on the keyboard?

Image1 Image2 While using visual studio code, I noticed that I can move a car forwards and backwards with the arrow keys on the keyboard. However, it doesn't seem to turn when I try to move in opposite directions. Is there a way to achieve this thro ...

the angular-ui-tinymce directive allows for seamless image uploads using a file browser

Utilizing jQuery, we have the ability to incorporate local images into the tinymce editor similar to what is demonstrated in this jsfiddle, by following the guidelines provided in the documentation. The Angular module for tinymce can be found at angular-u ...

I am looking for a way to have one element as a child of another element without automatically adopting specific properties

https://i.sstatic.net/iuNB7.png <span id="priority-dot-open-menu"> <span id="priority-menu"> <span class="tooltip-top"></span> <span id="priority-dot-blue">& ...

Error: Node-Sass - Unable to download win32-x64-57_binding.node

Currently in the process of getting a retired colleague's program up and running, but when attempting to execute meteor run I encounter this error. While loading package materialize:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Substitute any text string starting with a colon, such as the route path in Express

Below are some sample strings: const a = '/example/:someItemUuid/hello' const b = '/example/:someItemUuid/hello/:otherItemUuid' const params = { someItemUuid: '12345', otherItemUuid: '67890' } I am in search o ...

Guide on including a partial view in a modal using Jquery

Looking to enhance the parameters of a list of products by displaying a modal window for editing? You can achieve this by including a button in each row that triggers the modal window... https://i.sstatic.net/kDw6q.png The Edit button code in Index.csht ...

How can I show a div beneath a row in an HTML table?

Check out the code snippet below: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script> <style type="text/cs ...

Showing JSON arrays within innerHTML

One of my peers provided me with an array, and my task is to present it in an HTML format. Even after consulting various resources and examples, I am unable to display the required values. This is my first attempt at such a task, so any guidance would be ...

Getting the string value from a table row using JavaScript

I need to capture the value of result_status from the row labeled status. If all values in the row labeled status are 'pass', then the result_status will also be 'pass'. However, if any one of the values in the row labeled status is &a ...