Creating a JQuery slider that efficiently loads and displays groups of elements consecutively

Currently, I am in the process of developing an infinite horizontal tab slider using jQuery. My main objective is to optimize loading time by having the slider display only the first 10 slides upon initial page load. Subsequent slides will be loaded as the user navigates through them using the next page button.

The issue I am facing (available for reference on this demo) is that the slider currently loads one additional slide at a time and may cut off parts of the slides depending on the browser size. How can I address this problem effectively?

Below is the excerpt of JavaScript code that I have implemented:

var element = $('.tab-container li');
var slider = $('.tab-container');
var sliderWrapper = $('.wrapper');
var totalWidth = sliderWrapper.innerWidth();
var elementWidth = element.outerWidth();
var sliderWidth = 0;
var positionSlideX = slider.position().left;
var newPositionSlideX = 0;

sliderWrapper.append('<span class="prev-slide"><</span><span class="next-slide">></span>');

element.each(function() {
  sliderWidth = sliderWidth + $(this).outerWidth() + 1;
});

slider.css({
  'width': sliderWidth
});

$('.next-slide').click(function() {
  if (newPositionSlideX > (totalWidth - sliderWidth)) {
    newPositionSlideX = newPositionSlideX - elementWidth;
    slider.css({
      'left': newPositionSlideX
    }, check());
  };
});

$('.prev-slide').click(function() {
  if (newPositionSlideX >= -sliderWidth) {
    newPositionSlideX = newPositionSlideX + elementWidth;
    slider.css({
      'left': newPositionSlideX
    }, check());
  };
});

function check() {
  if (sliderWidth >= totalWidth && newPositionSlideX > (totalWidth - sliderWidth)) {
    $('.next-slide').css({
      'right': 0
    });
  } else {
    $('.next-slide').css({
      'right': -$(this).width()
    });
  };

  if (newPositionSlideX < 0) {
    $('.prev-slide').css({
      'left': 0
    });
  } else {
    $('.prev-slide').css({
      'left': -$(this).width()
    });
  };
};

$(window).resize(function() {
  totalWidth = sliderWrapper.innerWidth();
  check();
});
check();

Answer №1

If you want to streamline this process, consider keeping track of the index of the leftmost slide that is currently visible. This method is more commonly used.

var element = $('.tab-container li');
var slider = $('.tab-container');
var sliderWrapper = $('.wrapper');
var firstVisibleSlide = 0;
var nextButton;

sliderWrapper.prepend('<span class="prev-slide"><</span>').append('<span class="next-slide">></span>');

nextButton = $(".next-slide");

$('.next-slide').click(function() {
  if (slider.prop("offsetLeft") + slider.width() > nextButton.prop("offsetLeft")) {
        move(1);
  }
});

$('.prev-slide').click(function() {
  if (firstVisibleSlide > 0) {
    move(-1);
  };
});

function move(dif){ 
  var left;

  firstVisibleSlide += dif; 
  left = -1 * element.eq(firstVisibleSlide).prop("offsetLeft");
  slider.css({
      'left': left + "px"
  });
}

To improve performance when loading images, you can implement lazy loading by setting them as background properties as they become visible. You can easily keep track of the last visible slide in a similar manner to how you are tracking the first visible slide, and preload as many or as few images as desired.

Check out the updated fiddle here.

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

Disable event listener when the controls are unlocked using the pointerlock controls in three.js

While navigating a model with threejs pointerlock controls, clicking on specific sections of the model directs users to different parts of the site. However, an issue arises when the camera is centered over a section and the user exits the pointerlock. Upo ...

Steps to eliminate validation following the clearing of input fields

This is the code I've written for live validation using AJAX in an input field. My issue is that I want the validation to be removed if all inputs are deleted. <script type="text/javascript"> $(document).ready(function(){ ...

Setting the title of a document in Angular 5 using HTML escaped characters

It seems like a simple problem, but I can't seem to find an easy solution. Currently, I am using the Title service to add titles to my documents and everything is working fine. You can check out the documentation here: https://angular.io/guide/set-doc ...

Div element to animate and vanish in a flash

I'm attempting to create a smooth slide effect for a div element before it disappears. Below is the code I am currently using: function slideLeft(element) { $("#" + element).animate({ left: "510" }, { duration: 750 }); document.getEle ...

"Troubleshooting issue: jQuery AJAX encountering problems with parsing JSON

I recently came across a Uncaught SyntaxError: Unexpected end of input error in my code. var dataURL = "LineChartController?tp=" + tpAtt + "&dept=" + dept + "&date=" + dateMY; alert(dataURL); var JSONdata = jQuery.aja ...

How can you update an image's source when hovering over it?

My goal is to switch the image source upon mouseover using a combination of asp.net and javascript. Here is the code I am currently using: <asp:ImageButton id="button" runat="server" Height="65px" ImageUrl="~/images/logo.png" OnMouseOver="src='~ ...

When the mouse leaves, the gauge chart component's size will expand

I have encountered a problem while using the react-gauge-chart library in my react project. Within the project, I have integrated a popover component using material-ui and incorporated the gauge chart component from the library within the popover modal. T ...

Searching dynamically using class names with JQuery

I am seeking to create a dynamic search input based on the class names within the span tags. However, I am struggling with displaying the class name that I have identified. My goal is to show the class names that match the entered value in the input on the ...

What is the best method to "deactivate" a radio button while ensuring that a screen reader can still read the text and notify the user that it is inactive?

My current situation involves needing to deactivate certain radio buttons, while still having the option to reactivate them later. When I use the disabled attribute, screen readers will overlook this field and miss key information. I am seeking an accessi ...

displaying data in a table - adjust cell contents for smaller screens

I am currently designing an admin page using Bootstrap 5. I have implemented a data table with the following contents: On larger screen sizes: https://i.sstatic.net/2a9C1.png For smaller screen sizes (mobile phones), I have collapsed the action button as ...

Solving an object in ui-router state using ui-sref

Dealing with a large JSON object in an Angular controller and wanting to pass it to the controller of a template that will be displayed in a ui-view. I am aware that parameters can be passed to states using ui-sref, but I do not want this object to be visi ...

Troubleshooting error in data structure for nested dynamic routes with Next.js getStaticPaths

I am working on a page called [categories][price].js and I am attempting to achieve a particular data structure within the getStaticPaths function. For example, I want to have paths like cat1/10, cat1/20, cat1/30, cat2/10, cat2/20, etc. I came across this ...

Angular can be used to compare two arrays and display the matching values in a table

Having two arrays of objects, I attempted to compare them and display the matching values in a table. While looping through both arrays and comparing them by Id, I was able to find three matches. However, when trying to display these values in a table, onl ...

Using JavaScript to redirect to a different page while passing parameters

I've been experimenting with passing parameters from one ASP.NET page to another within our website by using JavaScript, jQuery, Ajax, Fetch, etc., and then capturing this parameter on the Load event of the redirected page using JavaScript. I'm u ...

The process of implementing server-side rendering for React Next applications with Material-ui using CSS

I have developed a basic React application using Next.js with an integrated express server: app.prepare() .then(() => { const server = express() server.get('/job/:id', (req, res) => { const actualPage = '/job' const ...

create a PDF document that contains interactive input fields which can be modified using Angular

My goal is to generate an editable PDF using JavaScript and AngularJS, allowing users to input data into text fields on the document. However, when I download the PDF, the text fields are not editable. Here is a snippet of the code: var opt = { margin ...

Can someone show me how to implement arrow functions within React components?

I am facing an issue while working on a node and react project. Whenever I use an arrow function, it shows an error stating that the function is not defined. Despite trying various tutorials and guides, I am unable to resolve this issue. Below is the snipp ...

I am struggling to make my table adapt to different screen sizes and become

Here is an example of a table: <TABLE class=vysledky > <TR class=podtrzeni> <TD width="39" height="19">Order <br /> League</TD> <TD width="39" height="19">Order <br /> Team</TD> <TD width="3 ...

Ways to layer two divs on each other and ensure button functionality is maintained

In the process of developing a ReactJS project, I encountered the challenge of overlapping my search bar autocomplete data with the result div located directly below it. For a more detailed understanding, please take a look at the provided image. Here&apo ...

I'm curious about the outcomes of the JavaScript test. Could someone provide an explanation

Recently, I was in the process of writing a blog post discussing the importance of checking for the existence of jQuery elements before attaching event handlers. To illustrate this, I quickly created a jsfiddle example here. What puzzles me is that the re ...