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

Is a preloader needed in a Vue.js app?

I'm currently exploring the world of Vue.js and could use some advice. When making a GET request using the axios package, I would like to display a preloader for the entire page until all the data has been loaded. While I know this is a common task i ...

After the child promise is resolved, have the parent function return a boolean value

I am currently faced with a challenge in my framework where the parent function must output either true or false>. However, I also need to perform an asynchronous operation within that function.</p> <p>How can I ensure that the parent functi ...

CSS not working when attempting to override Angular (13) Material file

In my Angular (13) application with Material, I have developed a CSS file specifically for overriding certain Material styles. This CSS file is imported into the styles.scss file as the last line. However, despite importing the external file, the CSS def ...

Implementing this type of route in Vue Router - What are the steps I should take?

I am currently delving into Vue and working on a project that involves creating a Vue application with a side menu for user navigation throughout the website. Utilizing Vue Router, my code structure looks like this: <template> <div id="app ...

Convert your Airbnb short link into the full link

I am currently developing an application that utilizes Airbnb links as part of its input. So far, I have identified two types of links: Long form, for example: . These are commonly used on desktop. Short form, such as: . These shorter links are often shar ...

Comparing strings with Ajax

I have been working on a basic ajax function setInterval(function() { var action = ''; var status = ''; $('#php-data').load('../Data/Dashboard.Data.php'); $.ajax({type: 'POST', u ...

The jQuery functions are unable to function properly when retrieving AJAX data

I am currently working on a script that inserts a record into my database using AJAX. After inserting the data, it is posted back in the following format... Print "<li>"; Print "<span class='cost'>" . $bill. "</span> "; Print ...

How to execute a java class method within a JSP page

Is there a way to trigger a specific Java method when I click a button on a JSP page? I attempted using a scriptlet in the onclick event of the button to create an instance of the class and call the desired method, but unfortunately, it didn't yield t ...

Can the ::before selector be used in HTML emails?

Hey there, I have a question that might sound silly but I'm having trouble finding an answer online. My issue is with styling the bullet point before a list item in an HTML email. All I want to do is change the bullet point to a square and give it a ...

JavaScript and jQuery code: Trigger the vjs-fade-out class to toggle when the userActive value in video.js changes

I am currently utilizing video.js to develop a player that is compatible with various devices. One crucial feature I have included is a custom "return to menu" button located in the top right corner of the video player. The challenge I am facing is dynamic ...

Validation for dates in Angular.Js input is important to ensure that only

Take a look at this form: <form name="user_submission" novalidate="novalidate" method="post"> <input type="date" name="date_of_birth" ng-focus="save_data()" ng-model-options="{timezone: 'UTC'}" ng-pattern="/^(19\d{2}|[2-9]& ...

How can I navigate to an anchor using hover?

I'm unsure if I can accomplish this task using just CSS and HTML or if I need to incorporate Javascript because my research did not yield much information on the subject. I have not attempted anything yet as I am uncertain about the approach I should ...

Strategies for limiting a table row in JavaScript or jQuery without utilizing the style tag or class attribute for that specific row

I am looking for a way to limit the display of records in a table. Currently, I can restrict the table rows using the style property, but this causes UI issues such as missing mouse-over effects for the entire row. I need to ensure that mouse-over functi ...

Using sl-vue-tree with vue-cli3.1 on internet explorer 11

Hello, I am a Japanese individual and my proficiency in English is lacking, so please bear with me. Currently, I am using vue-cli3.1 and I am looking to incorporate the sl-vue-tree module into my project for compatibility with ie11. The documentation menti ...

Incorporate a personalized style into the wysihtml5 text editor

Is there a way for me to insert a button that applies a custom class of my choice? I haven't been able to find this feature in the documentation, even though it's a commonly requested one. Here's an example of what I'm looking for: If ...

What is the best way to interact with a html element using the onclick event in Selenium?

Struggling to find the xpath for a link on a webpage. The HTML code for the link is as follows: <td style="width: 50%; text-align: right; vertical-align: middle"> <img id="ctl00_ContentPlaceHolder1_RadGrid1_ctl00_ctl02_ctl00_AddRecord1" ...

Utilizing Jquery for JSON Data Parsing

I have some JSON data that looks like this: {"product":["{productTitle=ABCD , productImage=/abcd.jpg, productPath=CDEF.html, productPrice=$299}","{productTitle=EFGH, productImage=xxxx.jpg, productPath=ggfft.html, productPrice=$299}"]} In my JSP page, I&a ...

Changing the value of a user object's variable in Django

I have been working on implementing a feature that allows users to edit their personal information in a Django project using Django forms. However, after entering new values in the form and hitting enter, the user is redirected back to the main profile pag ...

Exploring ways to style font families for individual options within ng-options

I am looking to display a combobox where each option has a different font. While using the ng-options directive in AngularJS to populate the options for a <select> tag, I am struggling to set the font-family for individual options. $scope.reportFon ...

Div not centered after translation by 50% on the Y-axis

My HTML and body have a height of 100vh. Inside my body, I have a square that is 100px by 100px. When I apply top: 50% to the div, it moves down 50%. But when I apply translateY(50%) to the div, it does not move down 50%. Why is this? Please note that y ...